[SyncFS] Add completion callback to PromoteDemotedChanges
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blobeefb09c11517d2634859f86196dadfb90b6a3f41
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 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));
69 return dict;
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,
78 NetLog* net_log)
79 : request_(NULL),
80 request_info_(request_info),
81 priority_(priority),
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),
87 session_(session),
88 stream_factory_(stream_factory),
89 next_state_(STATE_NONE),
90 pac_request_(NULL),
91 blocking_job_(NULL),
92 waiting_job_(NULL),
93 using_ssl_(false),
94 using_spdy_(false),
95 using_quic_(false),
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),
102 num_streams_(0),
103 spdy_session_direct_(false),
104 job_status_(STATUS_RUNNING),
105 other_job_status_(STATUS_RUNNING),
106 ptr_factory_(this) {
107 DCHECK(stream_factory);
108 DCHECK(session);
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();
119 connection_.reset();
122 if (pac_request_)
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) {
131 DCHECK(request);
132 request_ = request;
133 StartInternal();
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)) {
145 num_streams_ = 1;
146 } else {
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;
156 stream_.reset();
157 return RunLoop(OK);
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();
167 default:
168 return LOAD_STATE_IDLE;
172 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
173 const GURL& original_url,
174 AlternateProtocolInfo 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);
179 using_quic_ = true;
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_);
188 blocking_job_ = 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.
197 // Unblock |this|.
198 if (next_state_ == STATE_WAIT_FOR_JOB_COMPLETE) {
199 base::MessageLoop::current()->PostTask(
200 FROM_HERE,
201 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete,
202 ptr_factory_.GetWeakPtr(), OK));
206 void HttpStreamFactoryImpl::Job::Orphan(const Request* request) {
207 DCHECK_EQ(request_, request);
208 request_ = NULL;
209 if (blocking_job_) {
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
234 // preconnect state.
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 {
246 return using_spdy_;
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 {
258 return proxy_info_;
261 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
262 DCHECK(using_ssl_);
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
273 // origin server.
274 PrivacyMode privacy_mode = request_info_.privacy_mode;
275 if (IsHttpsProxyAndHttpUrl()) {
276 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
277 ProxyServer::Direct(),
278 privacy_mode);
279 } else {
280 return SpdySessionKey(origin_,
281 proxy_info_.proxy_server(),
282 privacy_mode);
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
293 // working.
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_);
303 if (IsOrphaned()) {
304 stream_factory_->OnOrphanedJobComplete(this);
305 } else {
306 request_->Complete(was_npn_negotiated(),
307 protocol_negotiated(),
308 using_spdy(),
309 net_log_);
310 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
311 stream_.release());
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
321 // never be ready.
322 DCHECK(!IsOrphaned());
323 request_->Complete(was_npn_negotiated(),
324 protocol_negotiated(),
325 using_spdy(),
326 net_log_);
327 request_->OnWebSocketHandshakeStreamReady(this,
328 server_ssl_config_,
329 proxy_info_,
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.
345 if (IsOrphaned()) {
346 if (spdy_session) {
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);
352 } else {
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());
361 if (IsOrphaned())
362 stream_factory_->OnOrphanedJobComplete(this);
363 else
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());
371 if (IsOrphaned())
372 stream_factory_->OnOrphanedJobComplete(this);
373 else
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());
382 if (IsOrphaned())
383 stream_factory_->OnOrphanedJobComplete(this);
384 else
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());
393 if (IsOrphaned())
394 stream_factory_->OnOrphanedJobComplete(this);
395 else
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());
404 if (IsOrphaned())
405 stream_factory_->OnOrphanedJobComplete(this);
406 else
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() {
413 DCHECK(!request_);
414 if (new_spdy_session_.get()) {
415 stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
416 spdy_session_direct_,
417 server_ssl_config_,
418 proxy_info_,
419 was_npn_negotiated(),
420 protocol_negotiated(),
421 using_spdy(),
422 net_log_);
424 stream_factory_->OnPreconnectsComplete(this);
425 // |this| may be deleted after this call.
428 // static
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.
437 return
438 spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
439 ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
442 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
443 RunLoop(result);
446 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
447 result = DoLoop(result);
449 if (result == ERR_IO_PENDING)
450 return result;
452 // If there was an error, we should have already resumed the |waiting_job_|,
453 // if there was one.
454 DCHECK(result == OK || waiting_job_ == NULL);
456 if (IsPreconnecting()) {
457 base::MessageLoop::current()->PostTask(
458 FROM_HERE,
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.
466 GetSSLInfo();
468 next_state_ = STATE_WAITING_USER_ACTION;
469 base::MessageLoop::current()->PostTask(
470 FROM_HERE,
471 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
472 ptr_factory_.GetWeakPtr(), result, ssl_info_));
473 return ERR_IO_PENDING;
476 switch (result) {
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(
489 FROM_HERE,
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(
498 FROM_HERE,
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(
511 FROM_HERE,
512 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
513 ptr_factory_.GetWeakPtr(),
514 *proxy_socket->GetConnectResponseInfo(),
515 proxy_socket->CreateConnectResponseStream()));
516 return ERR_IO_PENDING;
519 case OK:
520 job_status_ = STATUS_SUCCEEDED;
521 MaybeMarkAlternateProtocolBroken();
522 next_state_ = STATE_DONE;
523 if (new_spdy_session_.get()) {
524 base::MessageLoop::current()->PostTask(
525 FROM_HERE,
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(
531 FROM_HERE,
532 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
533 ptr_factory_.GetWeakPtr()));
534 } else {
535 DCHECK(stream_.get());
536 base::MessageLoop::current()->PostTask(
537 FROM_HERE,
538 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
540 return ERR_IO_PENDING;
542 default:
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(
549 FROM_HERE,
550 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
551 result));
552 return ERR_IO_PENDING;
556 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
557 DCHECK_NE(next_state_, STATE_NONE);
558 int rv = result;
559 do {
560 State state = next_state_;
561 next_state_ = STATE_NONE;
562 switch (state) {
563 case STATE_START:
564 DCHECK_EQ(OK, rv);
565 rv = DoStart();
566 break;
567 case STATE_RESOLVE_PROXY:
568 DCHECK_EQ(OK, rv);
569 rv = DoResolveProxy();
570 break;
571 case STATE_RESOLVE_PROXY_COMPLETE:
572 rv = DoResolveProxyComplete(rv);
573 break;
574 case STATE_WAIT_FOR_JOB:
575 DCHECK_EQ(OK, rv);
576 rv = DoWaitForJob();
577 break;
578 case STATE_WAIT_FOR_JOB_COMPLETE:
579 rv = DoWaitForJobComplete(rv);
580 break;
581 case STATE_INIT_CONNECTION:
582 DCHECK_EQ(OK, rv);
583 rv = DoInitConnection();
584 break;
585 case STATE_INIT_CONNECTION_COMPLETE:
586 rv = DoInitConnectionComplete(rv);
587 break;
588 case STATE_WAITING_USER_ACTION:
589 rv = DoWaitingUserAction(rv);
590 break;
591 case STATE_RESTART_TUNNEL_AUTH:
592 DCHECK_EQ(OK, rv);
593 rv = DoRestartTunnelAuth();
594 break;
595 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
596 rv = DoRestartTunnelAuthComplete(rv);
597 break;
598 case STATE_CREATE_STREAM:
599 DCHECK_EQ(OK, rv);
600 rv = DoCreateStream();
601 break;
602 case STATE_CREATE_STREAM_COMPLETE:
603 rv = DoCreateStreamComplete(rv);
604 break;
605 default:
606 NOTREACHED() << "bad state";
607 rv = ERR_FAILED;
608 break;
610 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
611 return rv;
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);
619 return 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_,
631 priority_));
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)) {
642 if (waiting_job_) {
643 waiting_job_->Resume(this);
644 waiting_job_ = NULL;
646 return ERR_UNSAFE_PORT;
649 next_state_ = STATE_RESOLVE_PROXY;
650 return OK;
653 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
654 DCHECK(!pac_request_);
655 DCHECK(session_);
657 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
659 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
660 proxy_info_.UseDirect();
661 return OK;
664 return session_->proxy_service()->ResolveProxy(
665 request_info_.url, request_info_.load_flags, &proxy_info_, io_callback_,
666 &pac_request_, session_->network_delegate(), net_log_);
669 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
670 pac_request_ = NULL;
672 if (result == OK) {
673 // Remove unsupported proxies from the list.
674 proxy_info_.RemoveProxiesWithoutScheme(
675 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_QUIC |
676 ProxyServer::SCHEME_HTTP | ProxyServer::SCHEME_HTTPS |
677 ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
679 if (proxy_info_.is_empty()) {
680 // No proxies/direct to choose from. This happens when we don't support
681 // any of the proxies in the returned list.
682 result = ERR_NO_SUPPORTED_PROXIES;
683 } else if (using_quic_ &&
684 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
685 // QUIC can not be spoken to non-QUIC proxies. This error should not be
686 // user visible, because the non-alternate job should be resumed.
687 result = ERR_NO_SUPPORTED_PROXIES;
691 if (result != OK) {
692 if (waiting_job_) {
693 waiting_job_->Resume(this);
694 waiting_job_ = NULL;
696 return result;
699 if (blocking_job_)
700 next_state_ = STATE_WAIT_FOR_JOB;
701 else
702 next_state_ = STATE_INIT_CONNECTION;
703 return OK;
706 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
707 bool rv = session_->params().force_spdy_always &&
708 session_->params().force_spdy_over_ssl;
709 return rv && !session_->HasSpdyExclusion(origin_);
712 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
713 bool rv = session_->params().force_spdy_always &&
714 !session_->params().force_spdy_over_ssl;
715 return rv && !session_->HasSpdyExclusion(origin_);
718 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
719 return session_->params().enable_quic &&
720 session_->params().origin_to_force_quic_on.Equals(origin_) &&
721 proxy_info_.is_direct();
724 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
725 DCHECK(blocking_job_);
726 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
727 return ERR_IO_PENDING;
730 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
731 DCHECK(!blocking_job_);
732 DCHECK_EQ(OK, result);
733 next_state_ = STATE_INIT_CONNECTION;
734 return OK;
737 int HttpStreamFactoryImpl::Job::DoInitConnection() {
738 DCHECK(!blocking_job_);
739 DCHECK(!connection_->is_initialized());
740 DCHECK(proxy_info_.proxy_server().is_valid());
741 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
743 using_ssl_ = request_info_.url.SchemeIs("https") ||
744 request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
745 using_spdy_ = false;
747 if (ShouldForceQuic())
748 using_quic_ = true;
750 if (proxy_info_.is_quic())
751 using_quic_ = true;
753 if (using_quic_) {
754 DCHECK(session_->params().enable_quic);
755 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
756 NOTREACHED();
757 // TODO(rch): support QUIC proxies for HTTPS urls.
758 return ERR_NOT_IMPLEMENTED;
760 HostPortPair destination = proxy_info_.is_quic() ?
761 proxy_info_.proxy_server().host_port_pair() : origin_;
762 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
763 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
764 int rv = quic_request_.Request(
765 destination, secure_quic, request_info_.privacy_mode,
766 request_info_.method, net_log_, io_callback_);
767 if (rv == OK) {
768 using_existing_quic_session_ = true;
769 } else {
770 // OK, there's no available QUIC session. Let |waiting_job_| resume
771 // if it's paused.
772 if (waiting_job_) {
773 waiting_job_->Resume(this);
774 waiting_job_ = NULL;
777 return rv;
780 // Check first if we have a spdy session for this group. If so, then go
781 // straight to using that.
782 SpdySessionKey spdy_session_key = GetSpdySessionKey();
783 base::WeakPtr<SpdySession> spdy_session =
784 session_->spdy_session_pool()->FindAvailableSession(
785 spdy_session_key, net_log_);
786 if (spdy_session && CanUseExistingSpdySession()) {
787 // If we're preconnecting, but we already have a SpdySession, we don't
788 // actually need to preconnect any sockets, so we're done.
789 if (IsPreconnecting())
790 return OK;
791 using_spdy_ = true;
792 next_state_ = STATE_CREATE_STREAM;
793 existing_spdy_session_ = spdy_session;
794 return OK;
795 } else if (request_ && !request_->HasSpdySessionKey() &&
796 (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
797 // Update the spdy session key for the request that launched this job.
798 request_->SetSpdySessionKey(spdy_session_key);
801 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
802 // paused.
804 if (waiting_job_) {
805 waiting_job_->Resume(this);
806 waiting_job_ = NULL;
809 if (proxy_info_.is_http() || proxy_info_.is_https())
810 establishing_tunnel_ = using_ssl_;
812 bool want_spdy_over_npn = original_url_ != NULL;
814 if (proxy_info_.is_https()) {
815 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
816 &proxy_ssl_config_,
817 true /* is a proxy server */);
818 // Disable revocation checking for HTTPS proxies since the revocation
819 // requests are probably going to need to go through the proxy too.
820 proxy_ssl_config_.rev_checking_enabled = false;
822 if (using_ssl_) {
823 InitSSLConfig(origin_, &server_ssl_config_,
824 false /* not a proxy server */);
827 if (IsPreconnecting()) {
828 DCHECK(!stream_factory_->for_websockets_);
829 return PreconnectSocketsForHttpRequest(
830 origin_url_,
831 request_info_.extra_headers,
832 request_info_.load_flags,
833 priority_,
834 session_,
835 proxy_info_,
836 ShouldForceSpdySSL(),
837 want_spdy_over_npn,
838 server_ssl_config_,
839 proxy_ssl_config_,
840 request_info_.privacy_mode,
841 net_log_,
842 num_streams_);
845 // If we can't use a SPDY session, don't both checking for one after
846 // the hostname is resolved.
847 OnHostResolutionCallback resolution_callback = CanUseExistingSpdySession() ?
848 base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
849 GetSpdySessionKey()) :
850 OnHostResolutionCallback();
851 if (stream_factory_->for_websockets_) {
852 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
853 SSLConfig websocket_server_ssl_config = server_ssl_config_;
854 websocket_server_ssl_config.next_protos.clear();
855 return InitSocketHandleForWebSocketRequest(
856 origin_url_, request_info_.extra_headers, request_info_.load_flags,
857 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
858 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
859 request_info_.privacy_mode, net_log_,
860 connection_.get(), resolution_callback, io_callback_);
863 return InitSocketHandleForHttpRequest(
864 origin_url_, request_info_.extra_headers, request_info_.load_flags,
865 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
866 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
867 request_info_.privacy_mode, net_log_,
868 connection_.get(), resolution_callback, io_callback_);
871 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
872 if (IsPreconnecting()) {
873 if (using_quic_)
874 return result;
875 DCHECK_EQ(OK, result);
876 return OK;
879 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
880 // We found a SPDY connection after resolving the host. This is
881 // probably an IP pooled connection.
882 SpdySessionKey spdy_session_key = GetSpdySessionKey();
883 existing_spdy_session_ =
884 session_->spdy_session_pool()->FindAvailableSession(
885 spdy_session_key, net_log_);
886 if (existing_spdy_session_) {
887 using_spdy_ = true;
888 next_state_ = STATE_CREATE_STREAM;
889 } else {
890 // It is possible that the spdy session no longer exists.
891 ReturnToStateInitConnection(true /* close connection */);
893 return OK;
896 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
897 // errors, such as ignoring certificate errors for Alternate-Protocol.
898 if (result < 0 && waiting_job_) {
899 waiting_job_->Resume(this);
900 waiting_job_ = NULL;
903 // |result| may be the result of any of the stacked pools. The following
904 // logic is used when determining how to interpret an error.
905 // If |result| < 0:
906 // and connection_->socket() != NULL, then the SSL handshake ran and it
907 // is a potentially recoverable error.
908 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
909 // then the SSL handshake ran with an unrecoverable error.
910 // otherwise, the error came from one of the other pools.
911 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
912 connection_->is_ssl_error());
914 if (ssl_started && (result == OK || IsCertificateError(result))) {
915 if (using_quic_ && result == OK) {
916 was_npn_negotiated_ = true;
917 NextProto protocol_negotiated =
918 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
919 protocol_negotiated_ = protocol_negotiated;
920 } else {
921 SSLClientSocket* ssl_socket =
922 static_cast<SSLClientSocket*>(connection_->socket());
923 if (ssl_socket->WasNpnNegotiated()) {
924 was_npn_negotiated_ = true;
925 std::string proto;
926 std::string server_protos;
927 SSLClientSocket::NextProtoStatus status =
928 ssl_socket->GetNextProto(&proto, &server_protos);
929 NextProto protocol_negotiated =
930 SSLClientSocket::NextProtoFromString(proto);
931 protocol_negotiated_ = protocol_negotiated;
932 net_log_.AddEvent(
933 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
934 base::Bind(&NetLogHttpStreamProtoCallback,
935 status, &proto, &server_protos));
936 if (ssl_socket->was_spdy_negotiated())
937 SwitchToSpdyMode();
939 if (ShouldForceSpdySSL())
940 SwitchToSpdyMode();
942 } else if (proxy_info_.is_https() && connection_->socket() &&
943 result == OK) {
944 ProxyClientSocket* proxy_socket =
945 static_cast<ProxyClientSocket*>(connection_->socket());
946 if (proxy_socket->IsUsingSpdy()) {
947 was_npn_negotiated_ = true;
948 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
949 SwitchToSpdyMode();
953 // We may be using spdy without SSL
954 if (ShouldForceSpdyWithoutSSL())
955 SwitchToSpdyMode();
957 if (result == ERR_PROXY_AUTH_REQUESTED ||
958 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
959 DCHECK(!ssl_started);
960 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
961 // SSL socket, but there was an error before that could happen. This
962 // puts the in progress HttpProxy socket into |connection_| in order to
963 // complete the auth (or read the response body). The tunnel restart code
964 // is careful to remove it before returning control to the rest of this
965 // class.
966 connection_.reset(connection_->release_pending_http_proxy_connection());
967 return result;
970 if (!ssl_started && result < 0 && original_url_.get()) {
971 job_status_ = STATUS_BROKEN;
972 MaybeMarkAlternateProtocolBroken();
973 return result;
976 if (using_quic_) {
977 if (result < 0) {
978 job_status_ = STATUS_BROKEN;
979 MaybeMarkAlternateProtocolBroken();
980 return result;
982 stream_ = quic_request_.ReleaseStream();
983 next_state_ = STATE_NONE;
984 return OK;
987 if (result < 0 && !ssl_started)
988 return ReconsiderProxyAfterError(result);
989 establishing_tunnel_ = false;
991 if (connection_->socket()) {
992 LogHttpConnectedMetrics(*connection_);
994 // We officially have a new connection. Record the type.
995 if (!connection_->is_reused()) {
996 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
997 UpdateConnectionTypeHistograms(type);
1001 // Handle SSL errors below.
1002 if (using_ssl_) {
1003 DCHECK(ssl_started);
1004 if (IsCertificateError(result)) {
1005 if (using_spdy_ && original_url_.get() &&
1006 original_url_->SchemeIs("http")) {
1007 // We ignore certificate errors for http over spdy.
1008 spdy_certificate_error_ = result;
1009 result = OK;
1010 } else {
1011 result = HandleCertificateError(result);
1012 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1013 ReturnToStateInitConnection(true /* close connection */);
1014 return result;
1018 if (result < 0)
1019 return result;
1022 next_state_ = STATE_CREATE_STREAM;
1023 return OK;
1026 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1027 // This state indicates that the stream request is in a partially
1028 // completed state, and we've called back to the delegate for more
1029 // information.
1031 // We're always waiting here for the delegate to call us back.
1032 return ERR_IO_PENDING;
1035 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1036 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1038 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1040 // We only set the socket motivation if we're the first to use
1041 // this socket. Is there a race for two SPDY requests? We really
1042 // need to plumb this through to the connect level.
1043 if (connection_->socket() && !connection_->is_reused())
1044 SetSocketMotivation();
1046 if (!using_spdy_) {
1047 // We may get ftp scheme when fetching ftp resources through proxy.
1048 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1049 (request_info_.url.SchemeIs("http") ||
1050 request_info_.url.SchemeIs("ftp"));
1051 if (stream_factory_->for_websockets_) {
1052 DCHECK(request_);
1053 DCHECK(request_->websocket_handshake_stream_create_helper());
1054 websocket_stream_.reset(
1055 request_->websocket_handshake_stream_create_helper()
1056 ->CreateBasicStream(connection_.Pass(), using_proxy));
1057 } else {
1058 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1060 return OK;
1063 CHECK(!stream_.get());
1065 bool direct = true;
1066 const ProxyServer& proxy_server = proxy_info_.proxy_server();
1067 PrivacyMode privacy_mode = request_info_.privacy_mode;
1068 SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1069 if (IsHttpsProxyAndHttpUrl()) {
1070 // If we don't have a direct SPDY session, and we're using an HTTPS
1071 // proxy, then we might have a SPDY session to the proxy.
1072 // We never use privacy mode for connection to proxy server.
1073 spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1074 ProxyServer::Direct(),
1075 PRIVACY_MODE_DISABLED);
1076 direct = false;
1079 base::WeakPtr<SpdySession> spdy_session;
1080 if (existing_spdy_session_.get()) {
1081 // We picked up an existing session, so we don't need our socket.
1082 if (connection_->socket())
1083 connection_->socket()->Disconnect();
1084 connection_->Reset();
1085 std::swap(spdy_session, existing_spdy_session_);
1086 } else {
1087 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1088 spdy_session = spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1089 if (!spdy_session) {
1090 base::WeakPtr<SpdySession> new_spdy_session =
1091 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1092 connection_.Pass(),
1093 net_log_,
1094 spdy_certificate_error_,
1095 using_ssl_);
1096 if (!new_spdy_session->HasAcceptableTransportSecurity()) {
1097 new_spdy_session->CloseSessionOnError(
1098 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1099 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1102 new_spdy_session_ = new_spdy_session;
1103 spdy_session_direct_ = direct;
1104 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1105 base::WeakPtr<HttpServerProperties> http_server_properties =
1106 session_->http_server_properties();
1107 if (http_server_properties)
1108 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1110 // Create a SpdyHttpStream attached to the session;
1111 // OnNewSpdySessionReadyCallback is not called until an event loop
1112 // iteration later, so if the SpdySession is closed between then, allow
1113 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1114 // bubble up to the request.
1115 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1116 stream_.reset(new SpdyHttpStream(new_spdy_session_, use_relative_url));
1118 return OK;
1122 if (!spdy_session)
1123 return ERR_CONNECTION_CLOSED;
1125 // TODO(willchan): Delete this code, because eventually, the
1126 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1127 // will know when SpdySessions become available.
1129 if (stream_factory_->for_websockets_) {
1130 // TODO(ricea): Restore this code when WebSockets over SPDY is implemented.
1131 NOTREACHED();
1132 } else {
1133 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1134 stream_.reset(new SpdyHttpStream(spdy_session, use_relative_url));
1136 return OK;
1139 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1140 if (result < 0)
1141 return result;
1143 session_->proxy_service()->ReportSuccess(proxy_info_);
1144 next_state_ = STATE_NONE;
1145 return OK;
1148 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1149 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1150 ProxyClientSocket* proxy_socket =
1151 static_cast<ProxyClientSocket*>(connection_->socket());
1152 return proxy_socket->RestartWithAuth(io_callback_);
1155 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1156 if (result == ERR_PROXY_AUTH_REQUESTED)
1157 return result;
1159 if (result == OK) {
1160 // Now that we've got the HttpProxyClientSocket connected. We have
1161 // to release it as an idle socket into the pool and start the connection
1162 // process from the beginning. Trying to pass it in with the
1163 // SSLSocketParams might cause a deadlock since params are dispatched
1164 // interchangeably. This request won't necessarily get this http proxy
1165 // socket, but there will be forward progress.
1166 establishing_tunnel_ = false;
1167 ReturnToStateInitConnection(false /* do not close connection */);
1168 return OK;
1171 return ReconsiderProxyAfterError(result);
1174 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1175 bool close_connection) {
1176 if (close_connection && connection_->socket())
1177 connection_->socket()->Disconnect();
1178 connection_->Reset();
1180 if (request_)
1181 request_->RemoveRequestFromSpdySessionRequestMap();
1183 next_state_ = STATE_INIT_CONNECTION;
1186 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1187 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1188 connection_->socket()->SetSubresourceSpeculation();
1189 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1190 connection_->socket()->SetOmniboxSpeculation();
1191 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1194 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1195 if (!proxy_info_.is_https())
1196 return false;
1197 if (original_url_.get()) {
1198 // We currently only support Alternate-Protocol where the original scheme
1199 // is http.
1200 DCHECK(original_url_->SchemeIs("http"));
1201 return original_url_->SchemeIs("http");
1203 return request_info_.url.SchemeIs("http");
1206 // Sets several fields of ssl_config for the given origin_server based on the
1207 // proxy info and other factors.
1208 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1209 const HostPortPair& origin_server,
1210 SSLConfig* ssl_config,
1211 bool is_proxy) const {
1212 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1213 // When connecting through an HTTPS proxy, disable TLS False Start so
1214 // that client authentication errors can be distinguished between those
1215 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1216 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1217 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1218 // TODO(rch): This assumes that the HTTPS proxy will only request a
1219 // client certificate during the initial handshake.
1220 // http://crbug.com/59292
1221 ssl_config->false_start_enabled = false;
1224 enum {
1225 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1226 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1227 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1228 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1229 FALLBACK_MAX
1232 int fallback = FALLBACK_NONE;
1233 if (ssl_config->version_fallback) {
1234 switch (ssl_config->version_max) {
1235 case SSL_PROTOCOL_VERSION_SSL3:
1236 fallback = FALLBACK_SSL3;
1237 break;
1238 case SSL_PROTOCOL_VERSION_TLS1:
1239 fallback = FALLBACK_TLS1;
1240 break;
1241 case SSL_PROTOCOL_VERSION_TLS1_1:
1242 fallback = FALLBACK_TLS1_1;
1243 break;
1246 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1247 fallback, FALLBACK_MAX);
1249 // We also wish to measure the amount of fallback connections for a host that
1250 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1251 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1252 // caused by network middleware rather than buggy HTTPS servers.
1253 const std::string& host = origin_server.host();
1254 if (!is_proxy &&
1255 host.size() >= 10 &&
1256 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1257 (host.size() == 10 || host[host.size()-11] == '.')) {
1258 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1259 fallback, FALLBACK_MAX);
1262 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1263 ssl_config->verify_ev_cert = true;
1265 // Disable Channel ID if privacy mode is enabled.
1266 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1267 ssl_config->channel_id_enabled = false;
1271 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1272 DCHECK(!pac_request_);
1273 DCHECK(session_);
1275 // A failure to resolve the hostname or any error related to establishing a
1276 // TCP connection could be grounds for trying a new proxy configuration.
1278 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1279 // to proxy servers. The hostname in those URLs might fail to resolve if we
1280 // are still using a non-proxy config. We need to check if a proxy config
1281 // now exists that corresponds to a proxy server that could load the URL.
1283 switch (error) {
1284 case ERR_PROXY_CONNECTION_FAILED:
1285 case ERR_NAME_NOT_RESOLVED:
1286 case ERR_INTERNET_DISCONNECTED:
1287 case ERR_ADDRESS_UNREACHABLE:
1288 case ERR_CONNECTION_CLOSED:
1289 case ERR_CONNECTION_TIMED_OUT:
1290 case ERR_CONNECTION_RESET:
1291 case ERR_CONNECTION_REFUSED:
1292 case ERR_CONNECTION_ABORTED:
1293 case ERR_TIMED_OUT:
1294 case ERR_TUNNEL_CONNECTION_FAILED:
1295 case ERR_SOCKS_CONNECTION_FAILED:
1296 // This can happen in the case of trying to talk to a proxy using SSL, and
1297 // ending up talking to a captive portal that supports SSL instead.
1298 case ERR_PROXY_CERTIFICATE_INVALID:
1299 // This can happen when trying to talk SSL to a non-SSL server (Like a
1300 // captive portal).
1301 case ERR_SSL_PROTOCOL_ERROR:
1302 break;
1303 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1304 // Remap the SOCKS-specific "host unreachable" error to a more
1305 // generic error code (this way consumers like the link doctor
1306 // know to substitute their error page).
1308 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1309 // differentiate between a proxy-side "host not found" versus a proxy-side
1310 // "address unreachable" error, and will report both of these failures as
1311 // ERR_ADDRESS_UNREACHABLE.
1312 return ERR_ADDRESS_UNREACHABLE;
1313 default:
1314 return error;
1317 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1318 return error;
1321 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1322 session_->ssl_client_auth_cache()->Remove(
1323 proxy_info_.proxy_server().host_port_pair());
1326 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1327 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1328 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1329 if (rv == OK || rv == ERR_IO_PENDING) {
1330 // If the error was during connection setup, there is no socket to
1331 // disconnect.
1332 if (connection_->socket())
1333 connection_->socket()->Disconnect();
1334 connection_->Reset();
1335 if (request_)
1336 request_->RemoveRequestFromSpdySessionRequestMap();
1337 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1338 } else {
1339 // If ReconsiderProxyAfterError() failed synchronously, it means
1340 // there was nothing left to fall-back to, so fail the transaction
1341 // with the last connection error we got.
1342 // TODO(eroman): This is a confusing contract, make it more obvious.
1343 rv = error;
1346 return rv;
1349 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1350 DCHECK(using_ssl_);
1351 DCHECK(IsCertificateError(error));
1353 SSLClientSocket* ssl_socket =
1354 static_cast<SSLClientSocket*>(connection_->socket());
1355 ssl_socket->GetSSLInfo(&ssl_info_);
1357 // Add the bad certificate to the set of allowed certificates in the
1358 // SSL config object. This data structure will be consulted after calling
1359 // RestartIgnoringLastError(). And the user will be asked interactively
1360 // before RestartIgnoringLastError() is ever called.
1361 SSLConfig::CertAndStatus bad_cert;
1363 // |ssl_info_.cert| may be NULL if we failed to create
1364 // X509Certificate for whatever reason, but normally it shouldn't
1365 // happen, unless this code is used inside sandbox.
1366 if (ssl_info_.cert.get() == NULL ||
1367 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1368 &bad_cert.der_cert)) {
1369 return error;
1371 bad_cert.cert_status = ssl_info_.cert_status;
1372 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1374 int load_flags = request_info_.load_flags;
1375 if (session_->params().ignore_certificate_errors)
1376 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1377 if (ssl_socket->IgnoreCertError(error, load_flags))
1378 return OK;
1379 return error;
1382 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1383 if (HttpStreamFactory::spdy_enabled())
1384 using_spdy_ = true;
1387 // static
1388 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1389 const ClientSocketHandle& handle) {
1390 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
1391 ClientSocketHandle::NUM_TYPES);
1393 switch (handle.reuse_type()) {
1394 case ClientSocketHandle::UNUSED:
1395 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1396 handle.setup_time(),
1397 base::TimeDelta::FromMilliseconds(1),
1398 base::TimeDelta::FromMinutes(10),
1399 100);
1400 break;
1401 case ClientSocketHandle::UNUSED_IDLE:
1402 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1403 handle.idle_time(),
1404 base::TimeDelta::FromMilliseconds(1),
1405 base::TimeDelta::FromMinutes(6),
1406 100);
1407 break;
1408 case ClientSocketHandle::REUSED_IDLE:
1409 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1410 handle.idle_time(),
1411 base::TimeDelta::FromMilliseconds(1),
1412 base::TimeDelta::FromMinutes(6),
1413 100);
1414 break;
1415 default:
1416 NOTREACHED();
1417 break;
1421 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1422 DCHECK_GE(num_streams_, 0);
1423 return num_streams_ > 0;
1426 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1427 return !IsPreconnecting() && !request_;
1430 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1431 net::AlternateProtocolExperiment alternate_protocol_experiment =
1432 ALTERNATE_PROTOCOL_NOT_PART_OF_EXPERIMENT;
1433 base::WeakPtr<HttpServerProperties> http_server_properties =
1434 session_->http_server_properties();
1435 if (http_server_properties) {
1436 alternate_protocol_experiment =
1437 http_server_properties->GetAlternateProtocolExperiment();
1439 if (using_existing_quic_session_) {
1440 // If an existing session was used, then no TCP connection was
1441 // started.
1442 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE,
1443 alternate_protocol_experiment);
1444 } else if (original_url_) {
1445 // This job was the alternate protocol job, and hence won the race.
1446 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE,
1447 alternate_protocol_experiment);
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,
1452 alternate_protocol_experiment);
1456 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1457 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1458 other_job_status_ = job.job_status_;
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