media: Specify WebRTC owners in media OWNERS file.
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blob45a0970b767dccd5723e8da6f2a6858a95b0863e
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"
7 #include <algorithm>
8 #include <string>
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"
41 namespace net {
43 // Returns parameters associated with the start of a HTTP stream job.
44 base::Value* NetLogHttpStreamJobCallback(const GURL* original_url,
45 const GURL* 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));
52 return dict;
55 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
56 // stream.
57 base::Value* NetLogHttpStreamProtoCallback(
58 const SSLClientSocket::NextProtoStatus status,
59 const std::string* proto,
60 NetLog::LogLevel /* log_level */) {
61 base::DictionaryValue* dict = new base::DictionaryValue();
63 dict->SetString("next_proto_status",
64 SSLClientSocket::NextProtoStatusToString(status));
65 dict->SetString("proto", *proto);
66 return dict;
69 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
70 HttpNetworkSession* session,
71 const HttpRequestInfo& request_info,
72 RequestPriority priority,
73 const SSLConfig& server_ssl_config,
74 const SSLConfig& proxy_ssl_config,
75 NetLog* net_log)
76 : request_(NULL),
77 request_info_(request_info),
78 priority_(priority),
79 server_ssl_config_(server_ssl_config),
80 proxy_ssl_config_(proxy_ssl_config),
81 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
82 io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
83 connection_(new ClientSocketHandle),
84 session_(session),
85 stream_factory_(stream_factory),
86 next_state_(STATE_NONE),
87 pac_request_(NULL),
88 blocking_job_(NULL),
89 waiting_job_(NULL),
90 using_ssl_(false),
91 using_spdy_(false),
92 using_quic_(false),
93 quic_request_(session_->quic_stream_factory()),
94 using_existing_quic_session_(false),
95 spdy_certificate_error_(OK),
96 establishing_tunnel_(false),
97 was_npn_negotiated_(false),
98 protocol_negotiated_(kProtoUnknown),
99 num_streams_(0),
100 spdy_session_direct_(false),
101 job_status_(STATUS_RUNNING),
102 other_job_status_(STATUS_RUNNING),
103 ptr_factory_(this) {
104 DCHECK(stream_factory);
105 DCHECK(session);
108 HttpStreamFactoryImpl::Job::~Job() {
109 net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
111 // When we're in a partially constructed state, waiting for the user to
112 // provide certificate handling information or authentication, we can't reuse
113 // this stream at all.
114 if (next_state_ == STATE_WAITING_USER_ACTION) {
115 connection_->socket()->Disconnect();
116 connection_.reset();
119 if (pac_request_)
120 session_->proxy_service()->CancelPacRequest(pac_request_);
122 // The stream could be in a partial state. It is not reusable.
123 if (stream_.get() && next_state_ != STATE_DONE)
124 stream_->Close(true /* not reusable */);
127 void HttpStreamFactoryImpl::Job::Start(Request* request) {
128 DCHECK(request);
129 request_ = request;
130 StartInternal();
133 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
134 DCHECK_GT(num_streams, 0);
135 base::WeakPtr<HttpServerProperties> http_server_properties =
136 session_->http_server_properties();
137 if (http_server_properties &&
138 http_server_properties->SupportsRequestPriority(
139 HostPortPair::FromURL(request_info_.url))) {
140 num_streams_ = 1;
141 } else {
142 num_streams_ = num_streams;
144 return StartInternal();
147 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
148 const AuthCredentials& credentials) {
149 DCHECK(establishing_tunnel_);
150 next_state_ = STATE_RESTART_TUNNEL_AUTH;
151 stream_.reset();
152 return RunLoop(OK);
155 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
156 switch (next_state_) {
157 case STATE_RESOLVE_PROXY_COMPLETE:
158 return session_->proxy_service()->GetLoadState(pac_request_);
159 case STATE_INIT_CONNECTION_COMPLETE:
160 case STATE_CREATE_STREAM_COMPLETE:
161 return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
162 default:
163 return LOAD_STATE_IDLE;
167 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
168 const GURL& original_url,
169 AlternateProtocolInfo alternate) {
170 DCHECK(!original_url_.get());
171 original_url_.reset(new GURL(original_url));
172 alternate_protocol_ = alternate;
173 if (alternate.protocol == QUIC) {
174 DCHECK(session_->params().enable_quic);
175 using_quic_ = true;
179 void HttpStreamFactoryImpl::Job::WaitFor(Job* job) {
180 DCHECK_EQ(STATE_NONE, next_state_);
181 DCHECK_EQ(STATE_NONE, job->next_state_);
182 DCHECK(!blocking_job_);
183 DCHECK(!job->waiting_job_);
184 blocking_job_ = job;
185 job->waiting_job_ = this;
188 void HttpStreamFactoryImpl::Job::Resume(Job* job) {
189 DCHECK_EQ(blocking_job_, job);
190 blocking_job_ = NULL;
192 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
193 // Unblock |this|.
194 if (next_state_ == STATE_WAIT_FOR_JOB_COMPLETE) {
195 base::MessageLoop::current()->PostTask(
196 FROM_HERE,
197 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete,
198 ptr_factory_.GetWeakPtr(), OK));
202 void HttpStreamFactoryImpl::Job::Orphan(const Request* request) {
203 DCHECK_EQ(request_, request);
204 request_ = NULL;
205 if (blocking_job_) {
206 // We've been orphaned, but there's a job we're blocked on. Don't bother
207 // racing, just cancel ourself.
208 DCHECK(blocking_job_->waiting_job_);
209 blocking_job_->waiting_job_ = NULL;
210 blocking_job_ = NULL;
211 if (stream_factory_->for_websockets_ &&
212 connection_ && connection_->socket()) {
213 connection_->socket()->Disconnect();
215 stream_factory_->OnOrphanedJobComplete(this);
216 } else if (stream_factory_->for_websockets_) {
217 // We cancel this job because a WebSocketHandshakeStream can't be created
218 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
219 // the Request class and isn't accessible from this job.
220 if (connection_ && connection_->socket()) {
221 connection_->socket()->Disconnect();
223 stream_factory_->OnOrphanedJobComplete(this);
227 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) {
228 priority_ = priority;
229 // TODO(akalin): Propagate this to |connection_| and maybe the
230 // preconnect state.
233 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
234 return was_npn_negotiated_;
237 NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const {
238 return protocol_negotiated_;
241 bool HttpStreamFactoryImpl::Job::using_spdy() const {
242 return using_spdy_;
245 const SSLConfig& HttpStreamFactoryImpl::Job::server_ssl_config() const {
246 return server_ssl_config_;
249 const SSLConfig& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
250 return proxy_ssl_config_;
253 const ProxyInfo& HttpStreamFactoryImpl::Job::proxy_info() const {
254 return proxy_info_;
257 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
258 DCHECK(using_ssl_);
259 DCHECK(!establishing_tunnel_);
260 DCHECK(connection_.get() && connection_->socket());
261 SSLClientSocket* ssl_socket =
262 static_cast<SSLClientSocket*>(connection_->socket());
263 ssl_socket->GetSSLInfo(&ssl_info_);
266 SpdySessionKey HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
267 // In the case that we're using an HTTPS proxy for an HTTP url,
268 // we look for a SPDY session *to* the proxy, instead of to the
269 // origin server.
270 PrivacyMode privacy_mode = request_info_.privacy_mode;
271 if (IsHttpsProxyAndHttpUrl()) {
272 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
273 ProxyServer::Direct(),
274 privacy_mode);
275 } else {
276 return SpdySessionKey(origin_,
277 proxy_info_.proxy_server(),
278 privacy_mode);
282 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
283 // We need to make sure that if a spdy session was created for
284 // https://somehost/ that we don't use that session for http://somehost:443/.
285 // The only time we can use an existing session is if the request URL is
286 // https (the normal case) or if we're connection to a SPDY proxy, or
287 // if we're running with force_spdy_always_. crbug.com/133176
288 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
289 // working.
290 return request_info_.url.SchemeIs("https") ||
291 proxy_info_.proxy_server().is_https() ||
292 session_->params().force_spdy_always;
295 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
296 DCHECK(stream_.get());
297 DCHECK(!IsPreconnecting());
298 DCHECK(!stream_factory_->for_websockets_);
299 if (IsOrphaned()) {
300 stream_factory_->OnOrphanedJobComplete(this);
301 } else {
302 request_->Complete(was_npn_negotiated(),
303 protocol_negotiated(),
304 using_spdy(),
305 net_log_);
306 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
307 stream_.release());
309 // |this| may be deleted after this call.
312 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
313 DCHECK(websocket_stream_);
314 DCHECK(!IsPreconnecting());
315 DCHECK(stream_factory_->for_websockets_);
316 // An orphaned WebSocket job will be closed immediately and
317 // never be ready.
318 DCHECK(!IsOrphaned());
319 request_->Complete(was_npn_negotiated(),
320 protocol_negotiated(),
321 using_spdy(),
322 net_log_);
323 request_->OnWebSocketHandshakeStreamReady(this,
324 server_ssl_config_,
325 proxy_info_,
326 websocket_stream_.release());
327 // |this| may be deleted after this call.
330 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
331 DCHECK(stream_.get());
332 DCHECK(!IsPreconnecting());
333 DCHECK(using_spdy());
334 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
335 // NULL at this point if the SpdySession closed immediately after creation.
336 base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
337 new_spdy_session_.reset();
339 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
340 // rather than notifying |request_| directly.
341 if (IsOrphaned()) {
342 if (spdy_session) {
343 stream_factory_->OnNewSpdySessionReady(
344 spdy_session, spdy_session_direct_, server_ssl_config_, proxy_info_,
345 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_);
347 stream_factory_->OnOrphanedJobComplete(this);
348 } else {
349 request_->OnNewSpdySessionReady(
350 this, stream_.Pass(), spdy_session, spdy_session_direct_);
352 // |this| may be deleted after this call.
355 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result) {
356 DCHECK(!IsPreconnecting());
357 if (IsOrphaned())
358 stream_factory_->OnOrphanedJobComplete(this);
359 else
360 request_->OnStreamFailed(this, result, server_ssl_config_);
361 // |this| may be deleted after this call.
364 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
365 int result, const SSLInfo& ssl_info) {
366 DCHECK(!IsPreconnecting());
367 if (IsOrphaned())
368 stream_factory_->OnOrphanedJobComplete(this);
369 else
370 request_->OnCertificateError(this, result, server_ssl_config_, ssl_info);
371 // |this| may be deleted after this call.
374 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
375 const HttpResponseInfo& response,
376 HttpAuthController* auth_controller) {
377 DCHECK(!IsPreconnecting());
378 if (IsOrphaned())
379 stream_factory_->OnOrphanedJobComplete(this);
380 else
381 request_->OnNeedsProxyAuth(
382 this, response, server_ssl_config_, proxy_info_, auth_controller);
383 // |this| may be deleted after this call.
386 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
387 SSLCertRequestInfo* cert_info) {
388 DCHECK(!IsPreconnecting());
389 if (IsOrphaned())
390 stream_factory_->OnOrphanedJobComplete(this);
391 else
392 request_->OnNeedsClientAuth(this, server_ssl_config_, cert_info);
393 // |this| may be deleted after this call.
396 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
397 const HttpResponseInfo& response_info,
398 HttpStream* stream) {
399 DCHECK(!IsPreconnecting());
400 if (IsOrphaned())
401 stream_factory_->OnOrphanedJobComplete(this);
402 else
403 request_->OnHttpsProxyTunnelResponse(
404 this, response_info, server_ssl_config_, proxy_info_, stream);
405 // |this| may be deleted after this call.
408 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
409 DCHECK(!request_);
410 if (new_spdy_session_.get()) {
411 stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
412 spdy_session_direct_,
413 server_ssl_config_,
414 proxy_info_,
415 was_npn_negotiated(),
416 protocol_negotiated(),
417 using_spdy(),
418 net_log_);
420 stream_factory_->OnPreconnectsComplete(this);
421 // |this| may be deleted after this call.
424 // static
425 int HttpStreamFactoryImpl::Job::OnHostResolution(
426 SpdySessionPool* spdy_session_pool,
427 const SpdySessionKey& spdy_session_key,
428 const AddressList& addresses,
429 const BoundNetLog& net_log) {
430 // It is OK to dereference spdy_session_pool, because the
431 // ClientSocketPoolManager will be destroyed in the same callback that
432 // destroys the SpdySessionPool.
433 return
434 spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
435 ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
438 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
439 RunLoop(result);
442 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
443 result = DoLoop(result);
445 if (result == ERR_IO_PENDING)
446 return result;
448 // If there was an error, we should have already resumed the |waiting_job_|,
449 // if there was one.
450 DCHECK(result == OK || waiting_job_ == NULL);
452 if (IsPreconnecting()) {
453 base::MessageLoop::current()->PostTask(
454 FROM_HERE,
455 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
456 ptr_factory_.GetWeakPtr()));
457 return ERR_IO_PENDING;
460 if (IsCertificateError(result)) {
461 // Retrieve SSL information from the socket.
462 GetSSLInfo();
464 next_state_ = STATE_WAITING_USER_ACTION;
465 base::MessageLoop::current()->PostTask(
466 FROM_HERE,
467 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
468 ptr_factory_.GetWeakPtr(), result, ssl_info_));
469 return ERR_IO_PENDING;
472 switch (result) {
473 case ERR_PROXY_AUTH_REQUESTED: {
474 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
475 connection_.get() != NULL);
476 if (!connection_.get())
477 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
478 CHECK(connection_->socket());
479 CHECK(establishing_tunnel_);
481 next_state_ = STATE_WAITING_USER_ACTION;
482 ProxyClientSocket* proxy_socket =
483 static_cast<ProxyClientSocket*>(connection_->socket());
484 base::MessageLoop::current()->PostTask(
485 FROM_HERE,
486 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
487 *proxy_socket->GetConnectResponseInfo(),
488 proxy_socket->GetAuthController()));
489 return ERR_IO_PENDING;
492 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
493 base::MessageLoop::current()->PostTask(
494 FROM_HERE,
495 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
496 connection_->ssl_error_response_info().cert_request_info));
497 return ERR_IO_PENDING;
499 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
500 DCHECK(connection_.get());
501 DCHECK(connection_->socket());
502 DCHECK(establishing_tunnel_);
504 ProxyClientSocket* proxy_socket =
505 static_cast<ProxyClientSocket*>(connection_->socket());
506 base::MessageLoop::current()->PostTask(
507 FROM_HERE,
508 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
509 ptr_factory_.GetWeakPtr(),
510 *proxy_socket->GetConnectResponseInfo(),
511 proxy_socket->CreateConnectResponseStream()));
512 return ERR_IO_PENDING;
515 case OK:
516 job_status_ = STATUS_SUCCEEDED;
517 MaybeMarkAlternateProtocolBroken();
518 next_state_ = STATE_DONE;
519 if (new_spdy_session_.get()) {
520 base::MessageLoop::current()->PostTask(
521 FROM_HERE,
522 base::Bind(&Job::OnNewSpdySessionReadyCallback,
523 ptr_factory_.GetWeakPtr()));
524 } else if (stream_factory_->for_websockets_) {
525 DCHECK(websocket_stream_);
526 base::MessageLoop::current()->PostTask(
527 FROM_HERE,
528 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
529 ptr_factory_.GetWeakPtr()));
530 } else {
531 DCHECK(stream_.get());
532 base::MessageLoop::current()->PostTask(
533 FROM_HERE,
534 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
536 return ERR_IO_PENDING;
538 default:
539 if (job_status_ != STATUS_BROKEN) {
540 DCHECK_EQ(STATUS_RUNNING, job_status_);
541 job_status_ = STATUS_FAILED;
542 MaybeMarkAlternateProtocolBroken();
544 base::MessageLoop::current()->PostTask(
545 FROM_HERE,
546 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
547 result));
548 return ERR_IO_PENDING;
552 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
553 DCHECK_NE(next_state_, STATE_NONE);
554 int rv = result;
555 do {
556 State state = next_state_;
557 next_state_ = STATE_NONE;
558 switch (state) {
559 case STATE_START:
560 DCHECK_EQ(OK, rv);
561 rv = DoStart();
562 break;
563 case STATE_RESOLVE_PROXY:
564 DCHECK_EQ(OK, rv);
565 rv = DoResolveProxy();
566 break;
567 case STATE_RESOLVE_PROXY_COMPLETE:
568 rv = DoResolveProxyComplete(rv);
569 break;
570 case STATE_WAIT_FOR_JOB:
571 DCHECK_EQ(OK, rv);
572 rv = DoWaitForJob();
573 break;
574 case STATE_WAIT_FOR_JOB_COMPLETE:
575 rv = DoWaitForJobComplete(rv);
576 break;
577 case STATE_INIT_CONNECTION:
578 DCHECK_EQ(OK, rv);
579 rv = DoInitConnection();
580 break;
581 case STATE_INIT_CONNECTION_COMPLETE:
582 rv = DoInitConnectionComplete(rv);
583 break;
584 case STATE_WAITING_USER_ACTION:
585 rv = DoWaitingUserAction(rv);
586 break;
587 case STATE_RESTART_TUNNEL_AUTH:
588 DCHECK_EQ(OK, rv);
589 rv = DoRestartTunnelAuth();
590 break;
591 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
592 rv = DoRestartTunnelAuthComplete(rv);
593 break;
594 case STATE_CREATE_STREAM:
595 DCHECK_EQ(OK, rv);
596 rv = DoCreateStream();
597 break;
598 case STATE_CREATE_STREAM_COMPLETE:
599 rv = DoCreateStreamComplete(rv);
600 break;
601 default:
602 NOTREACHED() << "bad state";
603 rv = ERR_FAILED;
604 break;
606 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
607 return rv;
610 int HttpStreamFactoryImpl::Job::StartInternal() {
611 CHECK_EQ(STATE_NONE, next_state_);
612 next_state_ = STATE_START;
613 int rv = RunLoop(OK);
614 DCHECK_EQ(ERR_IO_PENDING, rv);
615 return rv;
618 int HttpStreamFactoryImpl::Job::DoStart() {
619 origin_ = HostPortPair::FromURL(request_info_.url);
620 origin_url_ = stream_factory_->ApplyHostMappingRules(
621 request_info_.url, &origin_);
623 net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB,
624 base::Bind(&NetLogHttpStreamJobCallback,
625 &request_info_.url, &origin_url_,
626 priority_));
628 // Don't connect to restricted ports.
629 bool is_port_allowed = IsPortAllowedByDefault(origin_.port());
630 if (request_info_.url.SchemeIs("ftp")) {
631 // Never share connection with other jobs for FTP requests.
632 DCHECK(!waiting_job_);
634 is_port_allowed = IsPortAllowedByFtp(origin_.port());
636 if (!is_port_allowed && !IsPortAllowedByOverride(origin_.port())) {
637 if (waiting_job_) {
638 waiting_job_->Resume(this);
639 waiting_job_ = NULL;
641 return ERR_UNSAFE_PORT;
644 next_state_ = STATE_RESOLVE_PROXY;
645 return OK;
648 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
649 DCHECK(!pac_request_);
650 DCHECK(session_);
652 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
654 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
655 proxy_info_.UseDirect();
656 return OK;
659 return session_->proxy_service()->ResolveProxy(
660 request_info_.url, request_info_.load_flags, &proxy_info_, io_callback_,
661 &pac_request_, session_->network_delegate(), net_log_);
664 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
665 pac_request_ = NULL;
667 if (result == OK) {
668 // Remove unsupported proxies from the list.
669 proxy_info_.RemoveProxiesWithoutScheme(
670 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_QUIC |
671 ProxyServer::SCHEME_HTTP | ProxyServer::SCHEME_HTTPS |
672 ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
674 if (proxy_info_.is_empty()) {
675 // No proxies/direct to choose from. This happens when we don't support
676 // any of the proxies in the returned list.
677 result = ERR_NO_SUPPORTED_PROXIES;
678 } else if (using_quic_ &&
679 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
680 // QUIC can not be spoken to non-QUIC proxies. This error should not be
681 // user visible, because the non-alternate job should be resumed.
682 result = ERR_NO_SUPPORTED_PROXIES;
686 if (result != OK) {
687 if (waiting_job_) {
688 waiting_job_->Resume(this);
689 waiting_job_ = NULL;
691 return result;
694 if (blocking_job_)
695 next_state_ = STATE_WAIT_FOR_JOB;
696 else
697 next_state_ = STATE_INIT_CONNECTION;
698 return OK;
701 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
702 bool rv = session_->params().force_spdy_always &&
703 session_->params().force_spdy_over_ssl;
704 return rv && !session_->HasSpdyExclusion(origin_);
707 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
708 bool rv = session_->params().force_spdy_always &&
709 !session_->params().force_spdy_over_ssl;
710 return rv && !session_->HasSpdyExclusion(origin_);
713 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
714 return session_->params().enable_quic &&
715 session_->params().origin_to_force_quic_on.Equals(origin_) &&
716 proxy_info_.is_direct();
719 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
720 DCHECK(blocking_job_);
721 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
722 return ERR_IO_PENDING;
725 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
726 DCHECK(!blocking_job_);
727 DCHECK_EQ(OK, result);
728 next_state_ = STATE_INIT_CONNECTION;
729 return OK;
732 int HttpStreamFactoryImpl::Job::DoInitConnection() {
733 DCHECK(!blocking_job_);
734 DCHECK(!connection_->is_initialized());
735 DCHECK(proxy_info_.proxy_server().is_valid());
736 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
738 using_ssl_ = request_info_.url.SchemeIs("https") ||
739 request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
740 using_spdy_ = false;
742 if (ShouldForceQuic())
743 using_quic_ = true;
745 if (proxy_info_.is_quic())
746 using_quic_ = true;
748 if (using_quic_) {
749 DCHECK(session_->params().enable_quic);
750 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
751 NOTREACHED();
752 // TODO(rch): support QUIC proxies for HTTPS urls.
753 return ERR_NOT_IMPLEMENTED;
755 HostPortPair destination = proxy_info_.is_quic() ?
756 proxy_info_.proxy_server().host_port_pair() : origin_;
757 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
758 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
759 int rv = quic_request_.Request(
760 destination, secure_quic, request_info_.privacy_mode,
761 request_info_.method, net_log_, io_callback_);
762 if (rv == OK) {
763 using_existing_quic_session_ = true;
764 } else {
765 // OK, there's no available QUIC session. Let |waiting_job_| resume
766 // if it's paused.
767 if (waiting_job_) {
768 waiting_job_->Resume(this);
769 waiting_job_ = NULL;
772 return rv;
775 // Check first if we have a spdy session for this group. If so, then go
776 // straight to using that.
777 SpdySessionKey spdy_session_key = GetSpdySessionKey();
778 base::WeakPtr<SpdySession> spdy_session =
779 session_->spdy_session_pool()->FindAvailableSession(
780 spdy_session_key, net_log_);
781 if (spdy_session && CanUseExistingSpdySession()) {
782 // If we're preconnecting, but we already have a SpdySession, we don't
783 // actually need to preconnect any sockets, so we're done.
784 if (IsPreconnecting())
785 return OK;
786 using_spdy_ = true;
787 next_state_ = STATE_CREATE_STREAM;
788 existing_spdy_session_ = spdy_session;
789 return OK;
790 } else if (request_ && !request_->HasSpdySessionKey() &&
791 (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
792 // Update the spdy session key for the request that launched this job.
793 request_->SetSpdySessionKey(spdy_session_key);
796 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
797 // paused.
799 if (waiting_job_) {
800 waiting_job_->Resume(this);
801 waiting_job_ = NULL;
804 if (proxy_info_.is_http() || proxy_info_.is_https())
805 establishing_tunnel_ = using_ssl_;
807 bool want_spdy_over_npn = original_url_ != NULL;
809 if (proxy_info_.is_https()) {
810 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
811 &proxy_ssl_config_,
812 true /* is a proxy server */);
813 // Disable revocation checking for HTTPS proxies since the revocation
814 // requests are probably going to need to go through the proxy too.
815 proxy_ssl_config_.rev_checking_enabled = false;
817 if (using_ssl_) {
818 InitSSLConfig(origin_, &server_ssl_config_,
819 false /* not a proxy server */);
822 base::WeakPtr<HttpServerProperties> http_server_properties =
823 session_->http_server_properties();
824 if (http_server_properties) {
825 http_server_properties->MaybeForceHTTP11(origin_, &server_ssl_config_);
826 if (proxy_info_.is_http() || proxy_info_.is_https()) {
827 http_server_properties->MaybeForceHTTP11(
828 proxy_info_.proxy_server().host_port_pair(), &proxy_ssl_config_);
832 if (IsPreconnecting()) {
833 DCHECK(!stream_factory_->for_websockets_);
834 return PreconnectSocketsForHttpRequest(
835 origin_url_,
836 request_info_.extra_headers,
837 request_info_.load_flags,
838 priority_,
839 session_,
840 proxy_info_,
841 ShouldForceSpdySSL(),
842 want_spdy_over_npn,
843 server_ssl_config_,
844 proxy_ssl_config_,
845 request_info_.privacy_mode,
846 net_log_,
847 num_streams_);
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_);
868 return InitSocketHandleForHttpRequest(
869 origin_url_, request_info_.extra_headers, request_info_.load_flags,
870 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
871 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
872 request_info_.privacy_mode, net_log_,
873 connection_.get(), resolution_callback, io_callback_);
876 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
877 if (IsPreconnecting()) {
878 if (using_quic_)
879 return result;
880 DCHECK_EQ(OK, result);
881 return OK;
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_) {
892 using_spdy_ = true;
893 next_state_ = STATE_CREATE_STREAM;
894 } else {
895 // It is possible that the spdy session no longer exists.
896 ReturnToStateInitConnection(true /* close connection */);
898 return OK;
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);
905 waiting_job_ = NULL;
908 // |result| may be the result of any of the stacked pools. The following
909 // logic is used when determining how to interpret an error.
910 // If |result| < 0:
911 // and connection_->socket() != NULL, then the SSL handshake ran and it
912 // is a potentially recoverable error.
913 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
914 // then the SSL handshake ran with an unrecoverable error.
915 // otherwise, the error came from one of the other pools.
916 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
917 connection_->is_ssl_error());
919 if (ssl_started && (result == OK || IsCertificateError(result))) {
920 if (using_quic_ && result == OK) {
921 was_npn_negotiated_ = true;
922 NextProto protocol_negotiated =
923 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
924 protocol_negotiated_ = protocol_negotiated;
925 } else {
926 SSLClientSocket* ssl_socket =
927 static_cast<SSLClientSocket*>(connection_->socket());
928 if (ssl_socket->WasNpnNegotiated()) {
929 was_npn_negotiated_ = true;
930 std::string proto;
931 SSLClientSocket::NextProtoStatus status =
932 ssl_socket->GetNextProto(&proto);
933 NextProto protocol_negotiated =
934 SSLClientSocket::NextProtoFromString(proto);
935 protocol_negotiated_ = protocol_negotiated;
936 net_log_.AddEvent(
937 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
938 base::Bind(&NetLogHttpStreamProtoCallback,
939 status, &proto));
940 if (ssl_socket->was_spdy_negotiated())
941 SwitchToSpdyMode();
943 if (ShouldForceSpdySSL())
944 SwitchToSpdyMode();
946 } else if (proxy_info_.is_https() && connection_->socket() &&
947 result == OK) {
948 ProxyClientSocket* proxy_socket =
949 static_cast<ProxyClientSocket*>(connection_->socket());
950 if (proxy_socket->IsUsingSpdy()) {
951 was_npn_negotiated_ = true;
952 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
953 SwitchToSpdyMode();
957 // We may be using spdy without SSL
958 if (ShouldForceSpdyWithoutSSL())
959 SwitchToSpdyMode();
961 if (result == ERR_PROXY_AUTH_REQUESTED ||
962 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
963 DCHECK(!ssl_started);
964 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
965 // SSL socket, but there was an error before that could happen. This
966 // puts the in progress HttpProxy socket into |connection_| in order to
967 // complete the auth (or read the response body). The tunnel restart code
968 // is careful to remove it before returning control to the rest of this
969 // class.
970 connection_.reset(connection_->release_pending_http_proxy_connection());
971 return result;
974 if (!ssl_started && result < 0 && original_url_.get()) {
975 job_status_ = STATUS_BROKEN;
976 MaybeMarkAlternateProtocolBroken();
977 return result;
980 if (using_quic_) {
981 if (result < 0) {
982 job_status_ = STATUS_BROKEN;
983 MaybeMarkAlternateProtocolBroken();
984 return result;
986 stream_ = quic_request_.ReleaseStream();
987 next_state_ = STATE_NONE;
988 return OK;
991 if (result < 0 && !ssl_started)
992 return ReconsiderProxyAfterError(result);
993 establishing_tunnel_ = false;
995 if (connection_->socket()) {
996 LogHttpConnectedMetrics(*connection_);
998 // We officially have a new connection. Record the type.
999 if (!connection_->is_reused()) {
1000 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
1001 UpdateConnectionTypeHistograms(type);
1005 // Handle SSL errors below.
1006 if (using_ssl_) {
1007 DCHECK(ssl_started);
1008 if (IsCertificateError(result)) {
1009 if (using_spdy_ && original_url_.get() &&
1010 original_url_->SchemeIs("http")) {
1011 // We ignore certificate errors for http over spdy.
1012 spdy_certificate_error_ = result;
1013 result = OK;
1014 } else {
1015 result = HandleCertificateError(result);
1016 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1017 ReturnToStateInitConnection(true /* close connection */);
1018 return result;
1022 if (result < 0)
1023 return result;
1026 next_state_ = STATE_CREATE_STREAM;
1027 return OK;
1030 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1031 // This state indicates that the stream request is in a partially
1032 // completed state, and we've called back to the delegate for more
1033 // information.
1035 // We're always waiting here for the delegate to call us back.
1036 return ERR_IO_PENDING;
1039 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1040 base::WeakPtr<SpdySession> session, bool direct) {
1041 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1042 // implemented.
1043 if (stream_factory_->for_websockets_)
1044 return ERR_NOT_IMPLEMENTED;
1046 // TODO(willchan): Delete this code, because eventually, the
1047 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1048 // will know when SpdySessions become available.
1050 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1051 stream_.reset(new SpdyHttpStream(session, use_relative_url));
1052 return OK;
1055 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1056 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1058 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1060 // We only set the socket motivation if we're the first to use
1061 // this socket. Is there a race for two SPDY requests? We really
1062 // need to plumb this through to the connect level.
1063 if (connection_->socket() && !connection_->is_reused())
1064 SetSocketMotivation();
1066 if (!using_spdy_) {
1067 // We may get ftp scheme when fetching ftp resources through proxy.
1068 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1069 (request_info_.url.SchemeIs("http") ||
1070 request_info_.url.SchemeIs("ftp"));
1071 if (stream_factory_->for_websockets_) {
1072 DCHECK(request_);
1073 DCHECK(request_->websocket_handshake_stream_create_helper());
1074 websocket_stream_.reset(
1075 request_->websocket_handshake_stream_create_helper()
1076 ->CreateBasicStream(connection_.Pass(), using_proxy));
1077 } else {
1078 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1080 return OK;
1083 CHECK(!stream_.get());
1085 bool direct = true;
1086 const ProxyServer& proxy_server = proxy_info_.proxy_server();
1087 PrivacyMode privacy_mode = request_info_.privacy_mode;
1088 if (IsHttpsProxyAndHttpUrl())
1089 direct = false;
1091 if (existing_spdy_session_.get()) {
1092 // We picked up an existing session, so we don't need our socket.
1093 if (connection_->socket())
1094 connection_->socket()->Disconnect();
1095 connection_->Reset();
1097 int set_result = SetSpdyHttpStream(existing_spdy_session_, direct);
1098 existing_spdy_session_.reset();
1099 return set_result;
1102 SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1103 if (IsHttpsProxyAndHttpUrl()) {
1104 // If we don't have a direct SPDY session, and we're using an HTTPS
1105 // proxy, then we might have a SPDY session to the proxy.
1106 // We never use privacy mode for connection to proxy server.
1107 spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1108 ProxyServer::Direct(),
1109 PRIVACY_MODE_DISABLED);
1112 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1113 base::WeakPtr<SpdySession> spdy_session =
1114 spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1116 if (spdy_session) {
1117 return SetSpdyHttpStream(spdy_session, direct);
1120 spdy_session =
1121 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1122 connection_.Pass(),
1123 net_log_,
1124 spdy_certificate_error_,
1125 using_ssl_);
1126 if (!spdy_session->HasAcceptableTransportSecurity()) {
1127 spdy_session->CloseSessionOnError(
1128 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1129 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1132 new_spdy_session_ = spdy_session;
1133 spdy_session_direct_ = direct;
1134 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1135 base::WeakPtr<HttpServerProperties> http_server_properties =
1136 session_->http_server_properties();
1137 if (http_server_properties)
1138 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1140 // Create a SpdyHttpStream attached to the session;
1141 // OnNewSpdySessionReadyCallback is not called until an event loop
1142 // iteration later, so if the SpdySession is closed between then, allow
1143 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1144 // bubble up to the request.
1145 return SetSpdyHttpStream(new_spdy_session_, spdy_session_direct_);
1148 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1149 if (result < 0)
1150 return result;
1152 session_->proxy_service()->ReportSuccess(proxy_info_,
1153 session_->network_delegate());
1154 next_state_ = STATE_NONE;
1155 return OK;
1158 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1159 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1160 ProxyClientSocket* proxy_socket =
1161 static_cast<ProxyClientSocket*>(connection_->socket());
1162 return proxy_socket->RestartWithAuth(io_callback_);
1165 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1166 if (result == ERR_PROXY_AUTH_REQUESTED)
1167 return result;
1169 if (result == OK) {
1170 // Now that we've got the HttpProxyClientSocket connected. We have
1171 // to release it as an idle socket into the pool and start the connection
1172 // process from the beginning. Trying to pass it in with the
1173 // SSLSocketParams might cause a deadlock since params are dispatched
1174 // interchangeably. This request won't necessarily get this http proxy
1175 // socket, but there will be forward progress.
1176 establishing_tunnel_ = false;
1177 ReturnToStateInitConnection(false /* do not close connection */);
1178 return OK;
1181 return ReconsiderProxyAfterError(result);
1184 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1185 bool close_connection) {
1186 if (close_connection && connection_->socket())
1187 connection_->socket()->Disconnect();
1188 connection_->Reset();
1190 if (request_)
1191 request_->RemoveRequestFromSpdySessionRequestMap();
1193 next_state_ = STATE_INIT_CONNECTION;
1196 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1197 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1198 connection_->socket()->SetSubresourceSpeculation();
1199 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1200 connection_->socket()->SetOmniboxSpeculation();
1201 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1204 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1205 if (!proxy_info_.is_https())
1206 return false;
1207 if (original_url_.get()) {
1208 // We currently only support Alternate-Protocol where the original scheme
1209 // is http.
1210 DCHECK(original_url_->SchemeIs("http"));
1211 return original_url_->SchemeIs("http");
1213 return request_info_.url.SchemeIs("http");
1216 // Sets several fields of ssl_config for the given origin_server based on the
1217 // proxy info and other factors.
1218 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1219 const HostPortPair& origin_server,
1220 SSLConfig* ssl_config,
1221 bool is_proxy) const {
1222 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1223 // When connecting through an HTTPS proxy, disable TLS False Start so
1224 // that client authentication errors can be distinguished between those
1225 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1226 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1227 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1228 // TODO(rch): This assumes that the HTTPS proxy will only request a
1229 // client certificate during the initial handshake.
1230 // http://crbug.com/59292
1231 ssl_config->false_start_enabled = false;
1234 enum {
1235 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1236 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1237 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1238 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1239 FALLBACK_MAX
1242 int fallback = FALLBACK_NONE;
1243 if (ssl_config->version_fallback) {
1244 switch (ssl_config->version_max) {
1245 case SSL_PROTOCOL_VERSION_SSL3:
1246 fallback = FALLBACK_SSL3;
1247 break;
1248 case SSL_PROTOCOL_VERSION_TLS1:
1249 fallback = FALLBACK_TLS1;
1250 break;
1251 case SSL_PROTOCOL_VERSION_TLS1_1:
1252 fallback = FALLBACK_TLS1_1;
1253 break;
1256 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1257 fallback, FALLBACK_MAX);
1259 // We also wish to measure the amount of fallback connections for a host that
1260 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1261 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1262 // caused by network middleware rather than buggy HTTPS servers.
1263 const std::string& host = origin_server.host();
1264 if (!is_proxy &&
1265 host.size() >= 10 &&
1266 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1267 (host.size() == 10 || host[host.size()-11] == '.')) {
1268 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1269 fallback, FALLBACK_MAX);
1272 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1273 ssl_config->verify_ev_cert = true;
1275 // Disable Channel ID if privacy mode is enabled.
1276 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1277 ssl_config->channel_id_enabled = false;
1281 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1282 DCHECK(!pac_request_);
1283 DCHECK(session_);
1285 // A failure to resolve the hostname or any error related to establishing a
1286 // TCP connection could be grounds for trying a new proxy configuration.
1288 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1289 // to proxy servers. The hostname in those URLs might fail to resolve if we
1290 // are still using a non-proxy config. We need to check if a proxy config
1291 // now exists that corresponds to a proxy server that could load the URL.
1293 switch (error) {
1294 case ERR_PROXY_CONNECTION_FAILED:
1295 case ERR_NAME_NOT_RESOLVED:
1296 case ERR_INTERNET_DISCONNECTED:
1297 case ERR_ADDRESS_UNREACHABLE:
1298 case ERR_CONNECTION_CLOSED:
1299 case ERR_CONNECTION_TIMED_OUT:
1300 case ERR_CONNECTION_RESET:
1301 case ERR_CONNECTION_REFUSED:
1302 case ERR_CONNECTION_ABORTED:
1303 case ERR_TIMED_OUT:
1304 case ERR_TUNNEL_CONNECTION_FAILED:
1305 case ERR_SOCKS_CONNECTION_FAILED:
1306 // This can happen in the case of trying to talk to a proxy using SSL, and
1307 // ending up talking to a captive portal that supports SSL instead.
1308 case ERR_PROXY_CERTIFICATE_INVALID:
1309 // This can happen when trying to talk SSL to a non-SSL server (Like a
1310 // captive portal).
1311 case ERR_SSL_PROTOCOL_ERROR:
1312 break;
1313 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1314 // Remap the SOCKS-specific "host unreachable" error to a more
1315 // generic error code (this way consumers like the link doctor
1316 // know to substitute their error page).
1318 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1319 // differentiate between a proxy-side "host not found" versus a proxy-side
1320 // "address unreachable" error, and will report both of these failures as
1321 // ERR_ADDRESS_UNREACHABLE.
1322 return ERR_ADDRESS_UNREACHABLE;
1323 default:
1324 return error;
1327 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1328 return error;
1331 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1332 session_->ssl_client_auth_cache()->Remove(
1333 proxy_info_.proxy_server().host_port_pair());
1336 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1337 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1338 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1339 if (rv == OK || rv == ERR_IO_PENDING) {
1340 // If the error was during connection setup, there is no socket to
1341 // disconnect.
1342 if (connection_->socket())
1343 connection_->socket()->Disconnect();
1344 connection_->Reset();
1345 if (request_)
1346 request_->RemoveRequestFromSpdySessionRequestMap();
1347 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1348 } else {
1349 // If ReconsiderProxyAfterError() failed synchronously, it means
1350 // there was nothing left to fall-back to, so fail the transaction
1351 // with the last connection error we got.
1352 // TODO(eroman): This is a confusing contract, make it more obvious.
1353 rv = error;
1356 return rv;
1359 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1360 DCHECK(using_ssl_);
1361 DCHECK(IsCertificateError(error));
1363 SSLClientSocket* ssl_socket =
1364 static_cast<SSLClientSocket*>(connection_->socket());
1365 ssl_socket->GetSSLInfo(&ssl_info_);
1367 // Add the bad certificate to the set of allowed certificates in the
1368 // SSL config object. This data structure will be consulted after calling
1369 // RestartIgnoringLastError(). And the user will be asked interactively
1370 // before RestartIgnoringLastError() is ever called.
1371 SSLConfig::CertAndStatus bad_cert;
1373 // |ssl_info_.cert| may be NULL if we failed to create
1374 // X509Certificate for whatever reason, but normally it shouldn't
1375 // happen, unless this code is used inside sandbox.
1376 if (ssl_info_.cert.get() == NULL ||
1377 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1378 &bad_cert.der_cert)) {
1379 return error;
1381 bad_cert.cert_status = ssl_info_.cert_status;
1382 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1384 int load_flags = request_info_.load_flags;
1385 if (session_->params().ignore_certificate_errors)
1386 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1387 if (ssl_socket->IgnoreCertError(error, load_flags))
1388 return OK;
1389 return error;
1392 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1393 if (HttpStreamFactory::spdy_enabled())
1394 using_spdy_ = true;
1397 // static
1398 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1399 const ClientSocketHandle& handle) {
1400 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
1401 ClientSocketHandle::NUM_TYPES);
1403 switch (handle.reuse_type()) {
1404 case ClientSocketHandle::UNUSED:
1405 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1406 handle.setup_time(),
1407 base::TimeDelta::FromMilliseconds(1),
1408 base::TimeDelta::FromMinutes(10),
1409 100);
1410 break;
1411 case ClientSocketHandle::UNUSED_IDLE:
1412 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1413 handle.idle_time(),
1414 base::TimeDelta::FromMilliseconds(1),
1415 base::TimeDelta::FromMinutes(6),
1416 100);
1417 break;
1418 case ClientSocketHandle::REUSED_IDLE:
1419 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1420 handle.idle_time(),
1421 base::TimeDelta::FromMilliseconds(1),
1422 base::TimeDelta::FromMinutes(6),
1423 100);
1424 break;
1425 default:
1426 NOTREACHED();
1427 break;
1431 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1432 DCHECK_GE(num_streams_, 0);
1433 return num_streams_ > 0;
1436 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1437 return !IsPreconnecting() && !request_;
1440 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1441 if (using_existing_quic_session_) {
1442 // If an existing session was used, then no TCP connection was
1443 // started.
1444 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE);
1445 } else if (original_url_) {
1446 // This job was the alternate protocol job, and hence won the race.
1447 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE);
1448 } else {
1449 // This job was the normal job, and hence the alternate protocol job lost
1450 // the race.
1451 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE);
1455 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1456 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1457 other_job_status_ = job.job_status_;
1458 other_job_alternate_protocol_ = job.alternate_protocol_;
1459 MaybeMarkAlternateProtocolBroken();
1462 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1463 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1464 return;
1466 bool is_alternate_protocol_job = original_url_.get() != NULL;
1467 if (is_alternate_protocol_job) {
1468 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1469 HistogramBrokenAlternateProtocolLocation(
1470 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1471 session_->http_server_properties()->SetBrokenAlternateProtocol(
1472 HostPortPair::FromURL(*original_url_));
1474 return;
1477 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1478 HistogramBrokenAlternateProtocolLocation(
1479 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1480 session_->http_server_properties()->SetBrokenAlternateProtocol(
1481 HostPortPair::FromURL(request_info_.url));
1485 } // namespace net