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 const std::string* server_protos,
61 NetLog::LogLevel /* log_level */) {
62 base::DictionaryValue* dict = new base::DictionaryValue();
64 dict->SetString("next_proto_status",
65 SSLClientSocket::NextProtoStatusToString(status));
66 dict->SetString("proto", *proto);
67 dict->SetString("server_protos",
68 SSLClientSocket::ServerProtosToString(*server_protos));
72 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
73 HttpNetworkSession* session,
74 const HttpRequestInfo& request_info,
75 RequestPriority priority,
76 const SSLConfig& server_ssl_config,
77 const SSLConfig& proxy_ssl_config,
80 request_info_(request_info),
82 server_ssl_config_(server_ssl_config),
83 proxy_ssl_config_(proxy_ssl_config),
84 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
85 io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
86 connection_(new ClientSocketHandle),
88 stream_factory_(stream_factory),
89 next_state_(STATE_NONE),
96 quic_request_(session_->quic_stream_factory()),
97 using_existing_quic_session_(false),
98 spdy_certificate_error_(OK),
99 establishing_tunnel_(false),
100 was_npn_negotiated_(false),
101 protocol_negotiated_(kProtoUnknown),
103 spdy_session_direct_(false),
104 job_status_(STATUS_RUNNING),
105 other_job_status_(STATUS_RUNNING),
107 DCHECK(stream_factory);
111 HttpStreamFactoryImpl::Job::~Job() {
112 net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
114 // When we're in a partially constructed state, waiting for the user to
115 // provide certificate handling information or authentication, we can't reuse
116 // this stream at all.
117 if (next_state_ == STATE_WAITING_USER_ACTION) {
118 connection_->socket()->Disconnect();
123 session_->proxy_service()->CancelPacRequest(pac_request_);
125 // The stream could be in a partial state. It is not reusable.
126 if (stream_.get() && next_state_ != STATE_DONE)
127 stream_->Close(true /* not reusable */);
130 void HttpStreamFactoryImpl::Job::Start(Request* request) {
136 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
137 DCHECK_GT(num_streams, 0);
138 HostPortPair origin_server =
139 HostPortPair(request_info_.url.HostNoBrackets(),
140 request_info_.url.EffectiveIntPort());
141 base::WeakPtr<HttpServerProperties> http_server_properties =
142 session_->http_server_properties();
143 if (http_server_properties &&
144 http_server_properties->SupportsSpdy(origin_server)) {
147 num_streams_ = num_streams;
149 return StartInternal();
152 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
153 const AuthCredentials& credentials) {
154 DCHECK(establishing_tunnel_);
155 next_state_ = STATE_RESTART_TUNNEL_AUTH;
160 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
161 switch (next_state_) {
162 case STATE_RESOLVE_PROXY_COMPLETE:
163 return session_->proxy_service()->GetLoadState(pac_request_);
164 case STATE_INIT_CONNECTION_COMPLETE:
165 case STATE_CREATE_STREAM_COMPLETE:
166 return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
168 return LOAD_STATE_IDLE;
172 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
173 const GURL& original_url,
174 PortAlternateProtocolPair alternate) {
175 DCHECK(!original_url_.get());
176 original_url_.reset(new GURL(original_url));
177 if (alternate.protocol == QUIC) {
178 DCHECK(session_->params().enable_quic);
183 void HttpStreamFactoryImpl::Job::WaitFor(Job* job) {
184 DCHECK_EQ(STATE_NONE, next_state_);
185 DCHECK_EQ(STATE_NONE, job->next_state_);
186 DCHECK(!blocking_job_);
187 DCHECK(!job->waiting_job_);
189 job->waiting_job_ = this;
192 void HttpStreamFactoryImpl::Job::Resume(Job* job) {
193 DCHECK_EQ(blocking_job_, job);
194 blocking_job_ = NULL;
196 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
198 if (next_state_ == STATE_WAIT_FOR_JOB_COMPLETE) {
199 base::MessageLoop::current()->PostTask(
201 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete,
202 ptr_factory_.GetWeakPtr(), OK));
206 void HttpStreamFactoryImpl::Job::Orphan(const Request* request) {
207 DCHECK_EQ(request_, request);
210 // We've been orphaned, but there's a job we're blocked on. Don't bother
211 // racing, just cancel ourself.
212 DCHECK(blocking_job_->waiting_job_);
213 blocking_job_->waiting_job_ = NULL;
214 blocking_job_ = NULL;
215 if (stream_factory_->for_websockets_ &&
216 connection_ && connection_->socket()) {
217 connection_->socket()->Disconnect();
219 stream_factory_->OnOrphanedJobComplete(this);
220 } else if (stream_factory_->for_websockets_) {
221 // We cancel this job because a WebSocketHandshakeStream can't be created
222 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
223 // the Request class and isn't accessible from this job.
224 if (connection_ && connection_->socket()) {
225 connection_->socket()->Disconnect();
227 stream_factory_->OnOrphanedJobComplete(this);
231 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) {
232 priority_ = priority;
233 // TODO(akalin): Propagate this to |connection_| and maybe the
237 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
238 return was_npn_negotiated_;
241 NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const {
242 return protocol_negotiated_;
245 bool HttpStreamFactoryImpl::Job::using_spdy() const {
249 const SSLConfig& HttpStreamFactoryImpl::Job::server_ssl_config() const {
250 return server_ssl_config_;
253 const SSLConfig& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
254 return proxy_ssl_config_;
257 const ProxyInfo& HttpStreamFactoryImpl::Job::proxy_info() const {
261 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
263 DCHECK(!establishing_tunnel_);
264 DCHECK(connection_.get() && connection_->socket());
265 SSLClientSocket* ssl_socket =
266 static_cast<SSLClientSocket*>(connection_->socket());
267 ssl_socket->GetSSLInfo(&ssl_info_);
270 SpdySessionKey HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
271 // In the case that we're using an HTTPS proxy for an HTTP url,
272 // we look for a SPDY session *to* the proxy, instead of to the
274 PrivacyMode privacy_mode = request_info_.privacy_mode;
275 if (IsHttpsProxyAndHttpUrl()) {
276 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
277 ProxyServer::Direct(),
280 return SpdySessionKey(origin_,
281 proxy_info_.proxy_server(),
286 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
287 // We need to make sure that if a spdy session was created for
288 // https://somehost/ that we don't use that session for http://somehost:443/.
289 // The only time we can use an existing session is if the request URL is
290 // https (the normal case) or if we're connection to a SPDY proxy, or
291 // if we're running with force_spdy_always_. crbug.com/133176
292 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
294 return request_info_.url.SchemeIs("https") ||
295 proxy_info_.proxy_server().is_https() ||
296 session_->params().force_spdy_always;
299 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
300 DCHECK(stream_.get());
301 DCHECK(!IsPreconnecting());
302 DCHECK(!stream_factory_->for_websockets_);
304 stream_factory_->OnOrphanedJobComplete(this);
306 request_->Complete(was_npn_negotiated(),
307 protocol_negotiated(),
310 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
313 // |this| may be deleted after this call.
316 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
317 DCHECK(websocket_stream_);
318 DCHECK(!IsPreconnecting());
319 DCHECK(stream_factory_->for_websockets_);
320 // An orphaned WebSocket job will be closed immediately and
322 DCHECK(!IsOrphaned());
323 request_->Complete(was_npn_negotiated(),
324 protocol_negotiated(),
327 request_->OnWebSocketHandshakeStreamReady(this,
330 websocket_stream_.release());
331 // |this| may be deleted after this call.
334 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
335 DCHECK(stream_.get());
336 DCHECK(!IsPreconnecting());
337 DCHECK(using_spdy());
338 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
339 // NULL at this point if the SpdySession closed immediately after creation.
340 base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
341 new_spdy_session_.reset();
343 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
344 // rather than notifying |request_| directly.
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 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
479 connection_.get() != NULL);
480 if (!connection_.get())
481 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
482 CHECK(connection_->socket());
483 CHECK(establishing_tunnel_);
485 next_state_ = STATE_WAITING_USER_ACTION;
486 ProxyClientSocket* proxy_socket =
487 static_cast<ProxyClientSocket*>(connection_->socket());
488 base::MessageLoop::current()->PostTask(
490 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
491 *proxy_socket->GetConnectResponseInfo(),
492 proxy_socket->GetAuthController()));
493 return ERR_IO_PENDING;
496 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
497 base::MessageLoop::current()->PostTask(
499 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
500 connection_->ssl_error_response_info().cert_request_info));
501 return ERR_IO_PENDING;
503 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
504 DCHECK(connection_.get());
505 DCHECK(connection_->socket());
506 DCHECK(establishing_tunnel_);
508 ProxyClientSocket* proxy_socket =
509 static_cast<ProxyClientSocket*>(connection_->socket());
510 base::MessageLoop::current()->PostTask(
512 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
513 ptr_factory_.GetWeakPtr(),
514 *proxy_socket->GetConnectResponseInfo(),
515 proxy_socket->CreateConnectResponseStream()));
516 return ERR_IO_PENDING;
520 job_status_ = STATUS_SUCCEEDED;
521 MaybeMarkAlternateProtocolBroken();
522 next_state_ = STATE_DONE;
523 if (new_spdy_session_.get()) {
524 base::MessageLoop::current()->PostTask(
526 base::Bind(&Job::OnNewSpdySessionReadyCallback,
527 ptr_factory_.GetWeakPtr()));
528 } else if (stream_factory_->for_websockets_) {
529 DCHECK(websocket_stream_);
530 base::MessageLoop::current()->PostTask(
532 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
533 ptr_factory_.GetWeakPtr()));
535 DCHECK(stream_.get());
536 base::MessageLoop::current()->PostTask(
538 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
540 return ERR_IO_PENDING;
543 if (job_status_ != STATUS_BROKEN) {
544 DCHECK_EQ(STATUS_RUNNING, job_status_);
545 job_status_ = STATUS_FAILED;
546 MaybeMarkAlternateProtocolBroken();
548 base::MessageLoop::current()->PostTask(
550 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
552 return ERR_IO_PENDING;
556 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
557 DCHECK_NE(next_state_, STATE_NONE);
560 State state = next_state_;
561 next_state_ = STATE_NONE;
567 case STATE_RESOLVE_PROXY:
569 rv = DoResolveProxy();
571 case STATE_RESOLVE_PROXY_COMPLETE:
572 rv = DoResolveProxyComplete(rv);
574 case STATE_WAIT_FOR_JOB:
578 case STATE_WAIT_FOR_JOB_COMPLETE:
579 rv = DoWaitForJobComplete(rv);
581 case STATE_INIT_CONNECTION:
583 rv = DoInitConnection();
585 case STATE_INIT_CONNECTION_COMPLETE:
586 rv = DoInitConnectionComplete(rv);
588 case STATE_WAITING_USER_ACTION:
589 rv = DoWaitingUserAction(rv);
591 case STATE_RESTART_TUNNEL_AUTH:
593 rv = DoRestartTunnelAuth();
595 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
596 rv = DoRestartTunnelAuthComplete(rv);
598 case STATE_CREATE_STREAM:
600 rv = DoCreateStream();
602 case STATE_CREATE_STREAM_COMPLETE:
603 rv = DoCreateStreamComplete(rv);
606 NOTREACHED() << "bad state";
610 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
614 int HttpStreamFactoryImpl::Job::StartInternal() {
615 CHECK_EQ(STATE_NONE, next_state_);
616 next_state_ = STATE_START;
617 int rv = RunLoop(OK);
618 DCHECK_EQ(ERR_IO_PENDING, rv);
622 int HttpStreamFactoryImpl::Job::DoStart() {
623 int port = request_info_.url.EffectiveIntPort();
624 origin_ = HostPortPair(request_info_.url.HostNoBrackets(), port);
625 origin_url_ = stream_factory_->ApplyHostMappingRules(
626 request_info_.url, &origin_);
628 net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB,
629 base::Bind(&NetLogHttpStreamJobCallback,
630 &request_info_.url, &origin_url_,
633 // Don't connect to restricted ports.
634 bool is_port_allowed = IsPortAllowedByDefault(port);
635 if (request_info_.url.SchemeIs("ftp")) {
636 // Never share connection with other jobs for FTP requests.
637 DCHECK(!waiting_job_);
639 is_port_allowed = IsPortAllowedByFtp(port);
641 if (!is_port_allowed && !IsPortAllowedByOverride(port)) {
643 waiting_job_->Resume(this);
646 return ERR_UNSAFE_PORT;
649 next_state_ = STATE_RESOLVE_PROXY;
653 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
654 DCHECK(!pac_request_);
656 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
658 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
659 proxy_info_.UseDirect();
663 return session_->proxy_service()->ResolveProxy(
664 request_info_.url, &proxy_info_, io_callback_, &pac_request_, net_log_);
667 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
671 // Remove unsupported proxies from the list.
672 proxy_info_.RemoveProxiesWithoutScheme(
673 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_QUIC |
674 ProxyServer::SCHEME_HTTP | ProxyServer::SCHEME_HTTPS |
675 ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
677 if (proxy_info_.is_empty()) {
678 // No proxies/direct to choose from. This happens when we don't support
679 // any of the proxies in the returned list.
680 result = ERR_NO_SUPPORTED_PROXIES;
681 } else if (using_quic_ &&
682 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
683 // QUIC can not be spoken to non-QUIC proxies. This error should not be
684 // user visible, because the non-alternate job should be resumed.
685 result = ERR_NO_SUPPORTED_PROXIES;
691 waiting_job_->Resume(this);
698 next_state_ = STATE_WAIT_FOR_JOB;
700 next_state_ = STATE_INIT_CONNECTION;
704 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
705 bool rv = session_->params().force_spdy_always &&
706 session_->params().force_spdy_over_ssl;
707 return rv && !session_->HasSpdyExclusion(origin_);
710 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
711 bool rv = session_->params().force_spdy_always &&
712 !session_->params().force_spdy_over_ssl;
713 return rv && !session_->HasSpdyExclusion(origin_);
716 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
717 return session_->params().enable_quic &&
718 session_->params().origin_to_force_quic_on.Equals(origin_) &&
719 proxy_info_.is_direct();
722 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
723 DCHECK(blocking_job_);
724 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
725 return ERR_IO_PENDING;
728 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
729 DCHECK(!blocking_job_);
730 DCHECK_EQ(OK, result);
731 next_state_ = STATE_INIT_CONNECTION;
735 int HttpStreamFactoryImpl::Job::DoInitConnection() {
736 DCHECK(!blocking_job_);
737 DCHECK(!connection_->is_initialized());
738 DCHECK(proxy_info_.proxy_server().is_valid());
739 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
741 using_ssl_ = request_info_.url.SchemeIs("https") ||
742 request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
745 if (ShouldForceQuic())
748 if (proxy_info_.is_quic())
752 DCHECK(session_->params().enable_quic);
753 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
755 // TODO(rch): support QUIC proxies for HTTPS urls.
756 return ERR_NOT_IMPLEMENTED;
758 HostPortPair destination = proxy_info_.is_quic() ?
759 proxy_info_.proxy_server().host_port_pair() : origin_;
760 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
761 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
762 int rv = quic_request_.Request(
763 destination, secure_quic, request_info_.privacy_mode,
764 request_info_.method, net_log_, io_callback_);
766 using_existing_quic_session_ = true;
768 // OK, there's no available QUIC session. Let |waiting_job_| resume
771 waiting_job_->Resume(this);
778 // Check first if we have a spdy session for this group. If so, then go
779 // straight to using that.
780 SpdySessionKey spdy_session_key = GetSpdySessionKey();
781 base::WeakPtr<SpdySession> spdy_session =
782 session_->spdy_session_pool()->FindAvailableSession(
783 spdy_session_key, net_log_);
784 if (spdy_session && CanUseExistingSpdySession()) {
785 // If we're preconnecting, but we already have a SpdySession, we don't
786 // actually need to preconnect any sockets, so we're done.
787 if (IsPreconnecting())
790 next_state_ = STATE_CREATE_STREAM;
791 existing_spdy_session_ = spdy_session;
793 } else if (request_ && !request_->HasSpdySessionKey() &&
794 (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
795 // Update the spdy session key for the request that launched this job.
796 request_->SetSpdySessionKey(spdy_session_key);
799 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
803 waiting_job_->Resume(this);
807 if (proxy_info_.is_http() || proxy_info_.is_https())
808 establishing_tunnel_ = using_ssl_;
810 bool want_spdy_over_npn = original_url_ != NULL;
812 if (proxy_info_.is_https()) {
813 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
815 true /* is a proxy server */);
816 // Disable revocation checking for HTTPS proxies since the revocation
817 // requests are probably going to need to go through the proxy too.
818 proxy_ssl_config_.rev_checking_enabled = false;
821 InitSSLConfig(origin_, &server_ssl_config_,
822 false /* not a proxy server */);
825 if (IsPreconnecting()) {
826 DCHECK(!stream_factory_->for_websockets_);
827 return PreconnectSocketsForHttpRequest(
829 request_info_.extra_headers,
830 request_info_.load_flags,
834 ShouldForceSpdySSL(),
838 request_info_.privacy_mode,
843 // If we can't use a SPDY session, don't both checking for one after
844 // the hostname is resolved.
845 OnHostResolutionCallback resolution_callback = CanUseExistingSpdySession() ?
846 base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
847 GetSpdySessionKey()) :
848 OnHostResolutionCallback();
849 if (stream_factory_->for_websockets_) {
850 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
851 SSLConfig websocket_server_ssl_config = server_ssl_config_;
852 websocket_server_ssl_config.next_protos.clear();
853 return InitSocketHandleForWebSocketRequest(
854 origin_url_, request_info_.extra_headers, request_info_.load_flags,
855 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
856 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
857 request_info_.privacy_mode, net_log_,
858 connection_.get(), resolution_callback, io_callback_);
861 return InitSocketHandleForHttpRequest(
862 origin_url_, request_info_.extra_headers, request_info_.load_flags,
863 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
864 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
865 request_info_.privacy_mode, net_log_,
866 connection_.get(), resolution_callback, io_callback_);
869 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
870 if (IsPreconnecting()) {
873 DCHECK_EQ(OK, result);
877 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
878 // We found a SPDY connection after resolving the host. This is
879 // probably an IP pooled connection.
880 SpdySessionKey spdy_session_key = GetSpdySessionKey();
881 existing_spdy_session_ =
882 session_->spdy_session_pool()->FindAvailableSession(
883 spdy_session_key, net_log_);
884 if (existing_spdy_session_) {
886 next_state_ = STATE_CREATE_STREAM;
888 // It is possible that the spdy session no longer exists.
889 ReturnToStateInitConnection(true /* close connection */);
894 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
895 // errors, such as ignoring certificate errors for Alternate-Protocol.
896 if (result < 0 && waiting_job_) {
897 waiting_job_->Resume(this);
901 // |result| may be the result of any of the stacked pools. The following
902 // logic is used when determining how to interpret an error.
904 // and connection_->socket() != NULL, then the SSL handshake ran and it
905 // is a potentially recoverable error.
906 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
907 // then the SSL handshake ran with an unrecoverable error.
908 // otherwise, the error came from one of the other pools.
909 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
910 connection_->is_ssl_error());
912 if (ssl_started && (result == OK || IsCertificateError(result))) {
913 if (using_quic_ && result == OK) {
914 was_npn_negotiated_ = true;
915 NextProto protocol_negotiated =
916 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
917 protocol_negotiated_ = protocol_negotiated;
919 SSLClientSocket* ssl_socket =
920 static_cast<SSLClientSocket*>(connection_->socket());
921 if (ssl_socket->WasNpnNegotiated()) {
922 was_npn_negotiated_ = true;
924 std::string server_protos;
925 SSLClientSocket::NextProtoStatus status =
926 ssl_socket->GetNextProto(&proto, &server_protos);
927 NextProto protocol_negotiated =
928 SSLClientSocket::NextProtoFromString(proto);
929 protocol_negotiated_ = protocol_negotiated;
931 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
932 base::Bind(&NetLogHttpStreamProtoCallback,
933 status, &proto, &server_protos));
934 if (ssl_socket->was_spdy_negotiated())
937 if (ShouldForceSpdySSL())
940 } else if (proxy_info_.is_https() && connection_->socket() &&
942 ProxyClientSocket* proxy_socket =
943 static_cast<ProxyClientSocket*>(connection_->socket());
944 if (proxy_socket->IsUsingSpdy()) {
945 was_npn_negotiated_ = true;
946 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
951 // We may be using spdy without SSL
952 if (ShouldForceSpdyWithoutSSL())
955 if (result == ERR_PROXY_AUTH_REQUESTED ||
956 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
957 DCHECK(!ssl_started);
958 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
959 // SSL socket, but there was an error before that could happen. This
960 // puts the in progress HttpProxy socket into |connection_| in order to
961 // complete the auth (or read the response body). The tunnel restart code
962 // is careful to remove it before returning control to the rest of this
964 connection_.reset(connection_->release_pending_http_proxy_connection());
968 if (!ssl_started && result < 0 && original_url_.get()) {
969 job_status_ = STATUS_BROKEN;
970 MaybeMarkAlternateProtocolBroken();
976 job_status_ = STATUS_BROKEN;
977 MaybeMarkAlternateProtocolBroken();
980 stream_ = quic_request_.ReleaseStream();
981 next_state_ = STATE_NONE;
985 if (result < 0 && !ssl_started)
986 return ReconsiderProxyAfterError(result);
987 establishing_tunnel_ = false;
989 if (connection_->socket()) {
990 LogHttpConnectedMetrics(*connection_);
992 // We officially have a new connection. Record the type.
993 if (!connection_->is_reused()) {
994 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
995 UpdateConnectionTypeHistograms(type);
999 // Handle SSL errors below.
1001 DCHECK(ssl_started);
1002 if (IsCertificateError(result)) {
1003 if (using_spdy_ && original_url_.get() &&
1004 original_url_->SchemeIs("http")) {
1005 // We ignore certificate errors for http over spdy.
1006 spdy_certificate_error_ = result;
1009 result = HandleCertificateError(result);
1010 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1011 ReturnToStateInitConnection(true /* close connection */);
1020 next_state_ = STATE_CREATE_STREAM;
1024 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1025 // This state indicates that the stream request is in a partially
1026 // completed state, and we've called back to the delegate for more
1029 // We're always waiting here for the delegate to call us back.
1030 return ERR_IO_PENDING;
1033 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1034 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1036 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1038 // We only set the socket motivation if we're the first to use
1039 // this socket. Is there a race for two SPDY requests? We really
1040 // need to plumb this through to the connect level.
1041 if (connection_->socket() && !connection_->is_reused())
1042 SetSocketMotivation();
1045 // We may get ftp scheme when fetching ftp resources through proxy.
1046 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1047 (request_info_.url.SchemeIs("http") ||
1048 request_info_.url.SchemeIs("ftp"));
1049 if (stream_factory_->for_websockets_) {
1051 DCHECK(request_->websocket_handshake_stream_create_helper());
1052 websocket_stream_.reset(
1053 request_->websocket_handshake_stream_create_helper()
1054 ->CreateBasicStream(connection_.Pass(), using_proxy));
1056 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1061 CHECK(!stream_.get());
1064 const ProxyServer& proxy_server = proxy_info_.proxy_server();
1065 PrivacyMode privacy_mode = request_info_.privacy_mode;
1066 SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1067 if (IsHttpsProxyAndHttpUrl()) {
1068 // If we don't have a direct SPDY session, and we're using an HTTPS
1069 // proxy, then we might have a SPDY session to the proxy.
1070 // We never use privacy mode for connection to proxy server.
1071 spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1072 ProxyServer::Direct(),
1073 PRIVACY_MODE_DISABLED);
1077 base::WeakPtr<SpdySession> spdy_session;
1078 if (existing_spdy_session_.get()) {
1079 // We picked up an existing session, so we don't need our socket.
1080 if (connection_->socket())
1081 connection_->socket()->Disconnect();
1082 connection_->Reset();
1083 std::swap(spdy_session, existing_spdy_session_);
1085 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1086 spdy_session = spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1087 if (!spdy_session) {
1088 base::WeakPtr<SpdySession> new_spdy_session =
1089 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1092 spdy_certificate_error_,
1094 if (!new_spdy_session->HasAcceptableTransportSecurity()) {
1095 new_spdy_session->CloseSessionOnError(
1096 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1097 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1100 new_spdy_session_ = new_spdy_session;
1101 spdy_session_direct_ = direct;
1102 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1103 base::WeakPtr<HttpServerProperties> http_server_properties =
1104 session_->http_server_properties();
1105 if (http_server_properties)
1106 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1108 // Create a SpdyHttpStream attached to the session;
1109 // OnNewSpdySessionReadyCallback is not called until an event loop
1110 // iteration later, so if the SpdySession is closed between then, allow
1111 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1112 // bubble up to the request.
1113 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1114 stream_.reset(new SpdyHttpStream(new_spdy_session_, use_relative_url));
1121 return ERR_CONNECTION_CLOSED;
1123 // TODO(willchan): Delete this code, because eventually, the
1124 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1125 // will know when SpdySessions become available.
1127 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1129 if (stream_factory_->for_websockets_)
1130 return ERR_NOT_IMPLEMENTED;
1132 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1133 stream_.reset(new SpdyHttpStream(spdy_session, use_relative_url));
1138 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1142 session_->proxy_service()->ReportSuccess(proxy_info_);
1143 next_state_ = STATE_NONE;
1147 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1148 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1149 ProxyClientSocket* proxy_socket =
1150 static_cast<ProxyClientSocket*>(connection_->socket());
1151 return proxy_socket->RestartWithAuth(io_callback_);
1154 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1155 if (result == ERR_PROXY_AUTH_REQUESTED)
1159 // Now that we've got the HttpProxyClientSocket connected. We have
1160 // to release it as an idle socket into the pool and start the connection
1161 // process from the beginning. Trying to pass it in with the
1162 // SSLSocketParams might cause a deadlock since params are dispatched
1163 // interchangeably. This request won't necessarily get this http proxy
1164 // socket, but there will be forward progress.
1165 establishing_tunnel_ = false;
1166 ReturnToStateInitConnection(false /* do not close connection */);
1170 return ReconsiderProxyAfterError(result);
1173 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1174 bool close_connection) {
1175 if (close_connection && connection_->socket())
1176 connection_->socket()->Disconnect();
1177 connection_->Reset();
1180 request_->RemoveRequestFromSpdySessionRequestMap();
1182 next_state_ = STATE_INIT_CONNECTION;
1185 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1186 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1187 connection_->socket()->SetSubresourceSpeculation();
1188 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1189 connection_->socket()->SetOmniboxSpeculation();
1190 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1193 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1194 if (!proxy_info_.is_https())
1196 if (original_url_.get()) {
1197 // We currently only support Alternate-Protocol where the original scheme
1199 DCHECK(original_url_->SchemeIs("http"));
1200 return original_url_->SchemeIs("http");
1202 return request_info_.url.SchemeIs("http");
1205 // Sets several fields of ssl_config for the given origin_server based on the
1206 // proxy info and other factors.
1207 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1208 const HostPortPair& origin_server,
1209 SSLConfig* ssl_config,
1210 bool is_proxy) const {
1211 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1212 // When connecting through an HTTPS proxy, disable TLS False Start so
1213 // that client authentication errors can be distinguished between those
1214 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1215 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1216 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1217 // TODO(rch): This assumes that the HTTPS proxy will only request a
1218 // client certificate during the initial handshake.
1219 // http://crbug.com/59292
1220 ssl_config->false_start_enabled = false;
1224 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1225 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1226 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1227 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1231 int fallback = FALLBACK_NONE;
1232 if (ssl_config->version_fallback) {
1233 switch (ssl_config->version_max) {
1234 case SSL_PROTOCOL_VERSION_SSL3:
1235 fallback = FALLBACK_SSL3;
1237 case SSL_PROTOCOL_VERSION_TLS1:
1238 fallback = FALLBACK_TLS1;
1240 case SSL_PROTOCOL_VERSION_TLS1_1:
1241 fallback = FALLBACK_TLS1_1;
1245 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1246 fallback, FALLBACK_MAX);
1248 // We also wish to measure the amount of fallback connections for a host that
1249 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1250 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1251 // caused by network middleware rather than buggy HTTPS servers.
1252 const std::string& host = origin_server.host();
1254 host.size() >= 10 &&
1255 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1256 (host.size() == 10 || host[host.size()-11] == '.')) {
1257 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1258 fallback, FALLBACK_MAX);
1261 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1262 ssl_config->verify_ev_cert = true;
1264 // Disable Channel ID if privacy mode is enabled.
1265 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1266 ssl_config->channel_id_enabled = false;
1270 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1271 DCHECK(!pac_request_);
1273 // A failure to resolve the hostname or any error related to establishing a
1274 // TCP connection could be grounds for trying a new proxy configuration.
1276 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1277 // to proxy servers. The hostname in those URLs might fail to resolve if we
1278 // are still using a non-proxy config. We need to check if a proxy config
1279 // now exists that corresponds to a proxy server that could load the URL.
1282 case ERR_PROXY_CONNECTION_FAILED:
1283 case ERR_NAME_NOT_RESOLVED:
1284 case ERR_INTERNET_DISCONNECTED:
1285 case ERR_ADDRESS_UNREACHABLE:
1286 case ERR_CONNECTION_CLOSED:
1287 case ERR_CONNECTION_TIMED_OUT:
1288 case ERR_CONNECTION_RESET:
1289 case ERR_CONNECTION_REFUSED:
1290 case ERR_CONNECTION_ABORTED:
1292 case ERR_TUNNEL_CONNECTION_FAILED:
1293 case ERR_SOCKS_CONNECTION_FAILED:
1294 // This can happen in the case of trying to talk to a proxy using SSL, and
1295 // ending up talking to a captive portal that supports SSL instead.
1296 case ERR_PROXY_CERTIFICATE_INVALID:
1297 // This can happen when trying to talk SSL to a non-SSL server (Like a
1299 case ERR_SSL_PROTOCOL_ERROR:
1301 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1302 // Remap the SOCKS-specific "host unreachable" error to a more
1303 // generic error code (this way consumers like the link doctor
1304 // know to substitute their error page).
1306 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1307 // differentiate between a proxy-side "host not found" versus a proxy-side
1308 // "address unreachable" error, and will report both of these failures as
1309 // ERR_ADDRESS_UNREACHABLE.
1310 return ERR_ADDRESS_UNREACHABLE;
1315 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1319 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1320 session_->ssl_client_auth_cache()->Remove(
1321 proxy_info_.proxy_server().host_port_pair());
1324 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1325 request_info_.url, error, &proxy_info_, io_callback_, &pac_request_,
1327 if (rv == OK || rv == ERR_IO_PENDING) {
1328 // If the error was during connection setup, there is no socket to
1330 if (connection_->socket())
1331 connection_->socket()->Disconnect();
1332 connection_->Reset();
1334 request_->RemoveRequestFromSpdySessionRequestMap();
1335 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1337 // If ReconsiderProxyAfterError() failed synchronously, it means
1338 // there was nothing left to fall-back to, so fail the transaction
1339 // with the last connection error we got.
1340 // TODO(eroman): This is a confusing contract, make it more obvious.
1347 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1349 DCHECK(IsCertificateError(error));
1351 SSLClientSocket* ssl_socket =
1352 static_cast<SSLClientSocket*>(connection_->socket());
1353 ssl_socket->GetSSLInfo(&ssl_info_);
1355 // Add the bad certificate to the set of allowed certificates in the
1356 // SSL config object. This data structure will be consulted after calling
1357 // RestartIgnoringLastError(). And the user will be asked interactively
1358 // before RestartIgnoringLastError() is ever called.
1359 SSLConfig::CertAndStatus bad_cert;
1361 // |ssl_info_.cert| may be NULL if we failed to create
1362 // X509Certificate for whatever reason, but normally it shouldn't
1363 // happen, unless this code is used inside sandbox.
1364 if (ssl_info_.cert.get() == NULL ||
1365 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1366 &bad_cert.der_cert)) {
1369 bad_cert.cert_status = ssl_info_.cert_status;
1370 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1372 int load_flags = request_info_.load_flags;
1373 if (session_->params().ignore_certificate_errors)
1374 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1375 if (ssl_socket->IgnoreCertError(error, load_flags))
1380 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1381 if (HttpStreamFactory::spdy_enabled())
1386 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1387 const ClientSocketHandle& handle) {
1388 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
1389 ClientSocketHandle::NUM_TYPES);
1391 switch (handle.reuse_type()) {
1392 case ClientSocketHandle::UNUSED:
1393 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1394 handle.setup_time(),
1395 base::TimeDelta::FromMilliseconds(1),
1396 base::TimeDelta::FromMinutes(10),
1399 case ClientSocketHandle::UNUSED_IDLE:
1400 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1402 base::TimeDelta::FromMilliseconds(1),
1403 base::TimeDelta::FromMinutes(6),
1406 case ClientSocketHandle::REUSED_IDLE:
1407 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1409 base::TimeDelta::FromMilliseconds(1),
1410 base::TimeDelta::FromMinutes(6),
1419 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1420 DCHECK_GE(num_streams_, 0);
1421 return num_streams_ > 0;
1424 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1425 return !IsPreconnecting() && !request_;
1428 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1429 net::AlternateProtocolExperiment alternate_protocol_experiment =
1430 ALTERNATE_PROTOCOL_NOT_PART_OF_EXPERIMENT;
1431 base::WeakPtr<HttpServerProperties> http_server_properties =
1432 session_->http_server_properties();
1433 if (http_server_properties) {
1434 alternate_protocol_experiment =
1435 http_server_properties->GetAlternateProtocolExperiment();
1437 if (using_existing_quic_session_) {
1438 // If an existing session was used, then no TCP connection was
1440 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE,
1441 alternate_protocol_experiment);
1442 } else if (original_url_) {
1443 // This job was the alternate protocol job, and hence won the race.
1444 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE,
1445 alternate_protocol_experiment);
1447 // This job was the normal job, and hence the alternate protocol job lost
1449 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE,
1450 alternate_protocol_experiment);
1454 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1455 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1456 other_job_status_ = job.job_status_;
1457 MaybeMarkAlternateProtocolBroken();
1460 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1461 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1464 bool is_alternate_protocol_job = original_url_.get() != NULL;
1465 if (is_alternate_protocol_job) {
1466 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1467 HistogramBrokenAlternateProtocolLocation(
1468 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1469 session_->http_server_properties()->SetBrokenAlternateProtocol(
1470 HostPortPair::FromURL(*original_url_));
1475 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1476 HistogramBrokenAlternateProtocolLocation(
1477 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1478 session_->http_server_properties()->SetBrokenAlternateProtocol(
1479 HostPortPair::FromURL(request_info_.url));