Rewrite AndroidSyncSettings to be significantly simpler.
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blob510d64efc260d81bf6bd0b7501526124b4c84846
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/profiler/scoped_tracker.h"
14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/values.h"
18 #include "build/build_config.h"
19 #include "net/base/connection_type_histograms.h"
20 #include "net/base/net_log.h"
21 #include "net/base/net_util.h"
22 #include "net/http/http_basic_stream.h"
23 #include "net/http/http_network_session.h"
24 #include "net/http/http_proxy_client_socket.h"
25 #include "net/http/http_proxy_client_socket_pool.h"
26 #include "net/http/http_request_info.h"
27 #include "net/http/http_server_properties.h"
28 #include "net/http/http_stream_factory.h"
29 #include "net/http/http_stream_factory_impl_request.h"
30 #include "net/quic/quic_http_stream.h"
31 #include "net/socket/client_socket_handle.h"
32 #include "net/socket/client_socket_pool.h"
33 #include "net/socket/client_socket_pool_manager.h"
34 #include "net/socket/socks_client_socket_pool.h"
35 #include "net/socket/ssl_client_socket.h"
36 #include "net/socket/ssl_client_socket_pool.h"
37 #include "net/spdy/spdy_http_stream.h"
38 #include "net/spdy/spdy_session.h"
39 #include "net/spdy/spdy_session_pool.h"
40 #include "net/ssl/ssl_cert_request_info.h"
42 namespace net {
44 // Returns parameters associated with the start of a HTTP stream job.
45 base::Value* NetLogHttpStreamJobCallback(const GURL* original_url,
46 const GURL* url,
47 RequestPriority priority,
48 NetLog::LogLevel /* log_level */) {
49 base::DictionaryValue* dict = new base::DictionaryValue();
50 dict->SetString("original_url", original_url->GetOrigin().spec());
51 dict->SetString("url", url->GetOrigin().spec());
52 dict->SetString("priority", RequestPriorityToString(priority));
53 return dict;
56 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
57 // stream.
58 base::Value* NetLogHttpStreamProtoCallback(
59 const SSLClientSocket::NextProtoStatus status,
60 const std::string* proto,
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 return dict;
70 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
71 HttpNetworkSession* session,
72 const HttpRequestInfo& request_info,
73 RequestPriority priority,
74 const SSLConfig& server_ssl_config,
75 const SSLConfig& proxy_ssl_config,
76 NetLog* net_log)
77 : request_(NULL),
78 request_info_(request_info),
79 priority_(priority),
80 server_ssl_config_(server_ssl_config),
81 proxy_ssl_config_(proxy_ssl_config),
82 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
83 io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
84 connection_(new ClientSocketHandle),
85 session_(session),
86 stream_factory_(stream_factory),
87 next_state_(STATE_NONE),
88 pac_request_(NULL),
89 blocking_job_(NULL),
90 waiting_job_(NULL),
91 using_ssl_(false),
92 using_spdy_(false),
93 using_quic_(false),
94 quic_request_(session_->quic_stream_factory()),
95 using_existing_quic_session_(false),
96 spdy_certificate_error_(OK),
97 establishing_tunnel_(false),
98 was_npn_negotiated_(false),
99 protocol_negotiated_(kProtoUnknown),
100 num_streams_(0),
101 spdy_session_direct_(false),
102 job_status_(STATUS_RUNNING),
103 other_job_status_(STATUS_RUNNING),
104 ptr_factory_(this) {
105 DCHECK(stream_factory);
106 DCHECK(session);
109 HttpStreamFactoryImpl::Job::~Job() {
110 net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
112 // When we're in a partially constructed state, waiting for the user to
113 // provide certificate handling information or authentication, we can't reuse
114 // this stream at all.
115 if (next_state_ == STATE_WAITING_USER_ACTION) {
116 connection_->socket()->Disconnect();
117 connection_.reset();
120 if (pac_request_)
121 session_->proxy_service()->CancelPacRequest(pac_request_);
123 // The stream could be in a partial state. It is not reusable.
124 if (stream_.get() && next_state_ != STATE_DONE)
125 stream_->Close(true /* not reusable */);
128 void HttpStreamFactoryImpl::Job::Start(Request* request) {
129 DCHECK(request);
130 request_ = request;
131 StartInternal();
134 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
135 DCHECK_GT(num_streams, 0);
136 base::WeakPtr<HttpServerProperties> http_server_properties =
137 session_->http_server_properties();
138 if (http_server_properties &&
139 http_server_properties->SupportsRequestPriority(
140 HostPortPair::FromURL(request_info_.url))) {
141 num_streams_ = 1;
142 } else {
143 num_streams_ = num_streams;
145 return StartInternal();
148 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
149 const AuthCredentials& credentials) {
150 DCHECK(establishing_tunnel_);
151 next_state_ = STATE_RESTART_TUNNEL_AUTH;
152 stream_.reset();
153 return RunLoop(OK);
156 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
157 switch (next_state_) {
158 case STATE_RESOLVE_PROXY_COMPLETE:
159 return session_->proxy_service()->GetLoadState(pac_request_);
160 case STATE_INIT_CONNECTION_COMPLETE:
161 case STATE_CREATE_STREAM_COMPLETE:
162 return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
163 default:
164 return LOAD_STATE_IDLE;
168 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
169 const GURL& original_url,
170 AlternateProtocolInfo alternate) {
171 DCHECK(!original_url_.get());
172 original_url_.reset(new GURL(original_url));
173 alternate_protocol_ = alternate;
174 if (alternate.protocol == QUIC) {
175 DCHECK(session_->params().enable_quic);
176 using_quic_ = true;
180 void HttpStreamFactoryImpl::Job::WaitFor(Job* job) {
181 DCHECK_EQ(STATE_NONE, next_state_);
182 DCHECK_EQ(STATE_NONE, job->next_state_);
183 DCHECK(!blocking_job_);
184 DCHECK(!job->waiting_job_);
185 blocking_job_ = job;
186 job->waiting_job_ = this;
189 void HttpStreamFactoryImpl::Job::Resume(Job* job) {
190 DCHECK_EQ(blocking_job_, job);
191 blocking_job_ = NULL;
193 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
194 // Unblock |this|.
195 if (next_state_ == STATE_WAIT_FOR_JOB_COMPLETE) {
196 base::MessageLoop::current()->PostTask(
197 FROM_HERE,
198 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete,
199 ptr_factory_.GetWeakPtr(), OK));
203 void HttpStreamFactoryImpl::Job::Orphan(const Request* request) {
204 DCHECK_EQ(request_, request);
205 request_ = NULL;
206 if (blocking_job_) {
207 // We've been orphaned, but there's a job we're blocked on. Don't bother
208 // racing, just cancel ourself.
209 DCHECK(blocking_job_->waiting_job_);
210 blocking_job_->waiting_job_ = NULL;
211 blocking_job_ = NULL;
212 if (stream_factory_->for_websockets_ &&
213 connection_ && connection_->socket()) {
214 connection_->socket()->Disconnect();
216 stream_factory_->OnOrphanedJobComplete(this);
217 } else if (stream_factory_->for_websockets_) {
218 // We cancel this job because a WebSocketHandshakeStream can't be created
219 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
220 // the Request class and isn't accessible from this job.
221 if (connection_ && connection_->socket()) {
222 connection_->socket()->Disconnect();
224 stream_factory_->OnOrphanedJobComplete(this);
228 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) {
229 priority_ = priority;
230 // TODO(akalin): Propagate this to |connection_| and maybe the
231 // preconnect state.
234 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
235 return was_npn_negotiated_;
238 NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const {
239 return protocol_negotiated_;
242 bool HttpStreamFactoryImpl::Job::using_spdy() const {
243 return using_spdy_;
246 const SSLConfig& HttpStreamFactoryImpl::Job::server_ssl_config() const {
247 return server_ssl_config_;
250 const SSLConfig& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
251 return proxy_ssl_config_;
254 const ProxyInfo& HttpStreamFactoryImpl::Job::proxy_info() const {
255 return proxy_info_;
258 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
259 DCHECK(using_ssl_);
260 DCHECK(!establishing_tunnel_);
261 DCHECK(connection_.get() && connection_->socket());
262 SSLClientSocket* ssl_socket =
263 static_cast<SSLClientSocket*>(connection_->socket());
264 ssl_socket->GetSSLInfo(&ssl_info_);
267 SpdySessionKey HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
268 // In the case that we're using an HTTPS proxy for an HTTP url,
269 // we look for a SPDY session *to* the proxy, instead of to the
270 // origin server.
271 PrivacyMode privacy_mode = request_info_.privacy_mode;
272 if (IsHttpsProxyAndHttpUrl()) {
273 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
274 ProxyServer::Direct(),
275 privacy_mode);
276 } else {
277 return SpdySessionKey(origin_,
278 proxy_info_.proxy_server(),
279 privacy_mode);
283 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
284 // We need to make sure that if a spdy session was created for
285 // https://somehost/ that we don't use that session for http://somehost:443/.
286 // The only time we can use an existing session is if the request URL is
287 // https (the normal case) or if we're connection to a SPDY proxy, or
288 // if we're running with force_spdy_always_. crbug.com/133176
289 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
290 // working.
291 return request_info_.url.SchemeIs("https") ||
292 proxy_info_.proxy_server().is_https() ||
293 session_->params().force_spdy_always;
296 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
297 DCHECK(stream_.get());
298 DCHECK(!IsPreconnecting());
299 DCHECK(!stream_factory_->for_websockets_);
300 if (IsOrphaned()) {
301 stream_factory_->OnOrphanedJobComplete(this);
302 } else {
303 request_->Complete(was_npn_negotiated(),
304 protocol_negotiated(),
305 using_spdy(),
306 net_log_);
307 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
308 stream_.release());
310 // |this| may be deleted after this call.
313 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
314 DCHECK(websocket_stream_);
315 DCHECK(!IsPreconnecting());
316 DCHECK(stream_factory_->for_websockets_);
317 // An orphaned WebSocket job will be closed immediately and
318 // never be ready.
319 DCHECK(!IsOrphaned());
320 request_->Complete(was_npn_negotiated(),
321 protocol_negotiated(),
322 using_spdy(),
323 net_log_);
324 request_->OnWebSocketHandshakeStreamReady(this,
325 server_ssl_config_,
326 proxy_info_,
327 websocket_stream_.release());
328 // |this| may be deleted after this call.
331 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
332 DCHECK(stream_.get());
333 DCHECK(!IsPreconnecting());
334 DCHECK(using_spdy());
335 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
336 // NULL at this point if the SpdySession closed immediately after creation.
337 base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
338 new_spdy_session_.reset();
340 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
341 // rather than notifying |request_| directly.
342 if (IsOrphaned()) {
343 if (spdy_session) {
344 stream_factory_->OnNewSpdySessionReady(
345 spdy_session, spdy_session_direct_, server_ssl_config_, proxy_info_,
346 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_);
348 stream_factory_->OnOrphanedJobComplete(this);
349 } else {
350 request_->OnNewSpdySessionReady(
351 this, stream_.Pass(), spdy_session, spdy_session_direct_);
353 // |this| may be deleted after this call.
356 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result) {
357 DCHECK(!IsPreconnecting());
358 if (IsOrphaned())
359 stream_factory_->OnOrphanedJobComplete(this);
360 else
361 request_->OnStreamFailed(this, result, server_ssl_config_);
362 // |this| may be deleted after this call.
365 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
366 int result, const SSLInfo& ssl_info) {
367 DCHECK(!IsPreconnecting());
368 if (IsOrphaned())
369 stream_factory_->OnOrphanedJobComplete(this);
370 else
371 request_->OnCertificateError(this, result, server_ssl_config_, ssl_info);
372 // |this| may be deleted after this call.
375 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
376 const HttpResponseInfo& response,
377 HttpAuthController* auth_controller) {
378 DCHECK(!IsPreconnecting());
379 if (IsOrphaned())
380 stream_factory_->OnOrphanedJobComplete(this);
381 else
382 request_->OnNeedsProxyAuth(
383 this, response, server_ssl_config_, proxy_info_, auth_controller);
384 // |this| may be deleted after this call.
387 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
388 SSLCertRequestInfo* cert_info) {
389 DCHECK(!IsPreconnecting());
390 if (IsOrphaned())
391 stream_factory_->OnOrphanedJobComplete(this);
392 else
393 request_->OnNeedsClientAuth(this, server_ssl_config_, cert_info);
394 // |this| may be deleted after this call.
397 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
398 const HttpResponseInfo& response_info,
399 HttpStream* stream) {
400 DCHECK(!IsPreconnecting());
401 if (IsOrphaned())
402 stream_factory_->OnOrphanedJobComplete(this);
403 else
404 request_->OnHttpsProxyTunnelResponse(
405 this, response_info, server_ssl_config_, proxy_info_, stream);
406 // |this| may be deleted after this call.
409 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
410 DCHECK(!request_);
411 if (new_spdy_session_.get()) {
412 stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
413 spdy_session_direct_,
414 server_ssl_config_,
415 proxy_info_,
416 was_npn_negotiated(),
417 protocol_negotiated(),
418 using_spdy(),
419 net_log_);
421 stream_factory_->OnPreconnectsComplete(this);
422 // |this| may be deleted after this call.
425 // static
426 int HttpStreamFactoryImpl::Job::OnHostResolution(
427 SpdySessionPool* spdy_session_pool,
428 const SpdySessionKey& spdy_session_key,
429 const AddressList& addresses,
430 const BoundNetLog& net_log) {
431 // It is OK to dereference spdy_session_pool, because the
432 // ClientSocketPoolManager will be destroyed in the same callback that
433 // destroys the SpdySessionPool.
434 return
435 spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
436 ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
439 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
440 RunLoop(result);
443 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
444 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
445 tracked_objects::ScopedTracker tracking_profile(
446 FROM_HERE_WITH_EXPLICIT_FUNCTION(
447 "455884 HttpStreamFactoryImpl::Job::RunLoop"));
448 result = DoLoop(result);
450 if (result == ERR_IO_PENDING)
451 return result;
453 // If there was an error, we should have already resumed the |waiting_job_|,
454 // if there was one.
455 DCHECK(result == OK || waiting_job_ == NULL);
457 if (IsPreconnecting()) {
458 base::MessageLoop::current()->PostTask(
459 FROM_HERE,
460 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
461 ptr_factory_.GetWeakPtr()));
462 return ERR_IO_PENDING;
465 if (IsCertificateError(result)) {
466 // Retrieve SSL information from the socket.
467 GetSSLInfo();
469 next_state_ = STATE_WAITING_USER_ACTION;
470 base::MessageLoop::current()->PostTask(
471 FROM_HERE,
472 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
473 ptr_factory_.GetWeakPtr(), result, ssl_info_));
474 return ERR_IO_PENDING;
477 switch (result) {
478 case ERR_PROXY_AUTH_REQUESTED: {
479 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
480 connection_.get() != NULL);
481 if (!connection_.get())
482 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
483 CHECK(connection_->socket());
484 CHECK(establishing_tunnel_);
486 next_state_ = STATE_WAITING_USER_ACTION;
487 ProxyClientSocket* proxy_socket =
488 static_cast<ProxyClientSocket*>(connection_->socket());
489 base::MessageLoop::current()->PostTask(
490 FROM_HERE,
491 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
492 *proxy_socket->GetConnectResponseInfo(),
493 proxy_socket->GetAuthController()));
494 return ERR_IO_PENDING;
497 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
498 base::MessageLoop::current()->PostTask(
499 FROM_HERE,
500 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
501 connection_->ssl_error_response_info().cert_request_info));
502 return ERR_IO_PENDING;
504 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
505 DCHECK(connection_.get());
506 DCHECK(connection_->socket());
507 DCHECK(establishing_tunnel_);
509 ProxyClientSocket* proxy_socket =
510 static_cast<ProxyClientSocket*>(connection_->socket());
511 base::MessageLoop::current()->PostTask(
512 FROM_HERE,
513 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
514 ptr_factory_.GetWeakPtr(),
515 *proxy_socket->GetConnectResponseInfo(),
516 proxy_socket->CreateConnectResponseStream()));
517 return ERR_IO_PENDING;
520 case OK:
521 job_status_ = STATUS_SUCCEEDED;
522 MaybeMarkAlternateProtocolBroken();
523 next_state_ = STATE_DONE;
524 if (new_spdy_session_.get()) {
525 base::MessageLoop::current()->PostTask(
526 FROM_HERE,
527 base::Bind(&Job::OnNewSpdySessionReadyCallback,
528 ptr_factory_.GetWeakPtr()));
529 } else if (stream_factory_->for_websockets_) {
530 DCHECK(websocket_stream_);
531 base::MessageLoop::current()->PostTask(
532 FROM_HERE,
533 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
534 ptr_factory_.GetWeakPtr()));
535 } else {
536 DCHECK(stream_.get());
537 base::MessageLoop::current()->PostTask(
538 FROM_HERE,
539 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
541 return ERR_IO_PENDING;
543 default:
544 if (job_status_ != STATUS_BROKEN) {
545 DCHECK_EQ(STATUS_RUNNING, job_status_);
546 job_status_ = STATUS_FAILED;
547 MaybeMarkAlternateProtocolBroken();
549 base::MessageLoop::current()->PostTask(
550 FROM_HERE,
551 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
552 result));
553 return ERR_IO_PENDING;
557 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
558 DCHECK_NE(next_state_, STATE_NONE);
559 int rv = result;
560 do {
561 State state = next_state_;
562 next_state_ = STATE_NONE;
563 switch (state) {
564 case STATE_START:
565 DCHECK_EQ(OK, rv);
566 rv = DoStart();
567 break;
568 case STATE_RESOLVE_PROXY:
569 DCHECK_EQ(OK, rv);
570 rv = DoResolveProxy();
571 break;
572 case STATE_RESOLVE_PROXY_COMPLETE:
573 rv = DoResolveProxyComplete(rv);
574 break;
575 case STATE_WAIT_FOR_JOB:
576 DCHECK_EQ(OK, rv);
577 rv = DoWaitForJob();
578 break;
579 case STATE_WAIT_FOR_JOB_COMPLETE:
580 rv = DoWaitForJobComplete(rv);
581 break;
582 case STATE_INIT_CONNECTION:
583 DCHECK_EQ(OK, rv);
584 rv = DoInitConnection();
585 break;
586 case STATE_INIT_CONNECTION_COMPLETE:
587 rv = DoInitConnectionComplete(rv);
588 break;
589 case STATE_WAITING_USER_ACTION:
590 rv = DoWaitingUserAction(rv);
591 break;
592 case STATE_RESTART_TUNNEL_AUTH:
593 DCHECK_EQ(OK, rv);
594 rv = DoRestartTunnelAuth();
595 break;
596 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
597 rv = DoRestartTunnelAuthComplete(rv);
598 break;
599 case STATE_CREATE_STREAM:
600 DCHECK_EQ(OK, rv);
601 rv = DoCreateStream();
602 break;
603 case STATE_CREATE_STREAM_COMPLETE:
604 rv = DoCreateStreamComplete(rv);
605 break;
606 default:
607 NOTREACHED() << "bad state";
608 rv = ERR_FAILED;
609 break;
611 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
612 return rv;
615 int HttpStreamFactoryImpl::Job::StartInternal() {
616 CHECK_EQ(STATE_NONE, next_state_);
617 next_state_ = STATE_START;
618 int rv = RunLoop(OK);
619 DCHECK_EQ(ERR_IO_PENDING, rv);
620 return rv;
623 int HttpStreamFactoryImpl::Job::DoStart() {
624 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
625 tracked_objects::ScopedTracker tracking_profile(
626 FROM_HERE_WITH_EXPLICIT_FUNCTION(
627 "455884 HttpStreamFactoryImpl::Job::DoStart"));
628 origin_ = HostPortPair::FromURL(request_info_.url);
629 origin_url_ = stream_factory_->ApplyHostMappingRules(
630 request_info_.url, &origin_);
632 net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB,
633 base::Bind(&NetLogHttpStreamJobCallback,
634 &request_info_.url, &origin_url_,
635 priority_));
637 // Don't connect to restricted ports.
638 bool is_port_allowed = IsPortAllowedByDefault(origin_.port());
639 if (request_info_.url.SchemeIs("ftp")) {
640 // Never share connection with other jobs for FTP requests.
641 DCHECK(!waiting_job_);
643 is_port_allowed = IsPortAllowedByFtp(origin_.port());
645 if (!is_port_allowed && !IsPortAllowedByOverride(origin_.port())) {
646 if (waiting_job_) {
647 waiting_job_->Resume(this);
648 waiting_job_ = NULL;
650 return ERR_UNSAFE_PORT;
653 next_state_ = STATE_RESOLVE_PROXY;
654 return OK;
657 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
658 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
659 tracked_objects::ScopedTracker tracking_profile(
660 FROM_HERE_WITH_EXPLICIT_FUNCTION(
661 "455884 HttpStreamFactoryImpl::Job::DoResolveProxy"));
662 DCHECK(!pac_request_);
663 DCHECK(session_);
665 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
667 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
668 proxy_info_.UseDirect();
669 return OK;
672 return session_->proxy_service()->ResolveProxy(
673 request_info_.url, request_info_.load_flags, &proxy_info_, io_callback_,
674 &pac_request_, session_->network_delegate(), net_log_);
677 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
678 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
679 tracked_objects::ScopedTracker tracking_profile(
680 FROM_HERE_WITH_EXPLICIT_FUNCTION(
681 "455884 HttpStreamFactoryImpl::Job::DoResolveProxyComplete"));
682 pac_request_ = NULL;
684 if (result == OK) {
685 // Remove unsupported proxies from the list.
686 int supported_proxies =
687 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP |
688 ProxyServer::SCHEME_HTTPS | ProxyServer::SCHEME_SOCKS4 |
689 ProxyServer::SCHEME_SOCKS5;
691 if (session_->params().enable_quic_for_proxies)
692 supported_proxies |= ProxyServer::SCHEME_QUIC;
694 proxy_info_.RemoveProxiesWithoutScheme(supported_proxies);
696 if (proxy_info_.is_empty()) {
697 // No proxies/direct to choose from. This happens when we don't support
698 // any of the proxies in the returned list.
699 result = ERR_NO_SUPPORTED_PROXIES;
700 } else if (using_quic_ &&
701 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
702 // QUIC can not be spoken to non-QUIC proxies. This error should not be
703 // user visible, because the non-alternate job should be resumed.
704 result = ERR_NO_SUPPORTED_PROXIES;
708 if (result != OK) {
709 if (waiting_job_) {
710 waiting_job_->Resume(this);
711 waiting_job_ = NULL;
713 return result;
716 if (blocking_job_)
717 next_state_ = STATE_WAIT_FOR_JOB;
718 else
719 next_state_ = STATE_INIT_CONNECTION;
720 return OK;
723 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
724 bool rv = session_->params().force_spdy_always &&
725 session_->params().force_spdy_over_ssl;
726 return rv && !session_->HasSpdyExclusion(origin_);
729 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
730 bool rv = session_->params().force_spdy_always &&
731 !session_->params().force_spdy_over_ssl;
732 return rv && !session_->HasSpdyExclusion(origin_);
735 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
736 return session_->params().enable_quic &&
737 session_->params().origin_to_force_quic_on.Equals(origin_) &&
738 proxy_info_.is_direct();
741 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
742 DCHECK(blocking_job_);
743 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
744 return ERR_IO_PENDING;
747 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
748 DCHECK(!blocking_job_);
749 DCHECK_EQ(OK, result);
750 next_state_ = STATE_INIT_CONNECTION;
751 return OK;
754 int HttpStreamFactoryImpl::Job::DoInitConnection() {
755 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
756 tracked_objects::ScopedTracker tracking_profile(
757 FROM_HERE_WITH_EXPLICIT_FUNCTION(
758 "455884 HttpStreamFactoryImpl::Job::DoInitConnection"));
759 DCHECK(!blocking_job_);
760 DCHECK(!connection_->is_initialized());
761 DCHECK(proxy_info_.proxy_server().is_valid());
762 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
764 using_ssl_ = request_info_.url.SchemeIs("https") ||
765 request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
766 using_spdy_ = false;
768 if (ShouldForceQuic())
769 using_quic_ = true;
771 DCHECK(!using_quic_ || session_->params().enable_quic);
773 if (proxy_info_.is_quic()) {
774 using_quic_ = true;
775 DCHECK(session_->params().enable_quic_for_proxies);
778 if (using_quic_) {
779 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
780 NOTREACHED();
781 // TODO(rch): support QUIC proxies for HTTPS urls.
782 return ERR_NOT_IMPLEMENTED;
784 HostPortPair destination = proxy_info_.is_quic() ?
785 proxy_info_.proxy_server().host_port_pair() : origin_;
786 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
787 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
788 int rv = quic_request_.Request(
789 destination, secure_quic, request_info_.privacy_mode,
790 request_info_.method, net_log_, io_callback_);
791 if (rv == OK) {
792 using_existing_quic_session_ = true;
793 } else {
794 // OK, there's no available QUIC session. Let |waiting_job_| resume
795 // if it's paused.
796 if (waiting_job_) {
797 waiting_job_->Resume(this);
798 waiting_job_ = NULL;
801 return rv;
804 // Check first if we have a spdy session for this group. If so, then go
805 // straight to using that.
806 SpdySessionKey spdy_session_key = GetSpdySessionKey();
807 base::WeakPtr<SpdySession> spdy_session =
808 session_->spdy_session_pool()->FindAvailableSession(
809 spdy_session_key, net_log_);
810 if (spdy_session && CanUseExistingSpdySession()) {
811 // If we're preconnecting, but we already have a SpdySession, we don't
812 // actually need to preconnect any sockets, so we're done.
813 if (IsPreconnecting())
814 return OK;
815 using_spdy_ = true;
816 next_state_ = STATE_CREATE_STREAM;
817 existing_spdy_session_ = spdy_session;
818 return OK;
819 } else if (request_ && !request_->HasSpdySessionKey() &&
820 (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
821 // Update the spdy session key for the request that launched this job.
822 request_->SetSpdySessionKey(spdy_session_key);
825 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
826 // paused.
828 if (waiting_job_) {
829 waiting_job_->Resume(this);
830 waiting_job_ = NULL;
833 if (proxy_info_.is_http() || proxy_info_.is_https())
834 establishing_tunnel_ = using_ssl_;
836 bool want_spdy_over_npn = original_url_ != NULL;
838 if (proxy_info_.is_https()) {
839 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
840 &proxy_ssl_config_,
841 true /* is a proxy server */);
842 // Disable revocation checking for HTTPS proxies since the revocation
843 // requests are probably going to need to go through the proxy too.
844 proxy_ssl_config_.rev_checking_enabled = false;
846 if (using_ssl_) {
847 InitSSLConfig(origin_, &server_ssl_config_,
848 false /* not a proxy server */);
851 base::WeakPtr<HttpServerProperties> http_server_properties =
852 session_->http_server_properties();
853 if (http_server_properties) {
854 http_server_properties->MaybeForceHTTP11(origin_, &server_ssl_config_);
855 if (proxy_info_.is_http() || proxy_info_.is_https()) {
856 http_server_properties->MaybeForceHTTP11(
857 proxy_info_.proxy_server().host_port_pair(), &proxy_ssl_config_);
861 if (IsPreconnecting()) {
862 DCHECK(!stream_factory_->for_websockets_);
863 return PreconnectSocketsForHttpRequest(
864 origin_url_,
865 request_info_.extra_headers,
866 request_info_.load_flags,
867 priority_,
868 session_,
869 proxy_info_,
870 ShouldForceSpdySSL(),
871 want_spdy_over_npn,
872 server_ssl_config_,
873 proxy_ssl_config_,
874 request_info_.privacy_mode,
875 net_log_,
876 num_streams_);
879 // If we can't use a SPDY session, don't both checking for one after
880 // the hostname is resolved.
881 OnHostResolutionCallback resolution_callback = CanUseExistingSpdySession() ?
882 base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
883 GetSpdySessionKey()) :
884 OnHostResolutionCallback();
885 if (stream_factory_->for_websockets_) {
886 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
887 SSLConfig websocket_server_ssl_config = server_ssl_config_;
888 websocket_server_ssl_config.next_protos.clear();
889 return InitSocketHandleForWebSocketRequest(
890 origin_url_, request_info_.extra_headers, request_info_.load_flags,
891 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
892 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
893 request_info_.privacy_mode, net_log_,
894 connection_.get(), resolution_callback, io_callback_);
897 return InitSocketHandleForHttpRequest(
898 origin_url_, request_info_.extra_headers, request_info_.load_flags,
899 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
900 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
901 request_info_.privacy_mode, net_log_,
902 connection_.get(), resolution_callback, io_callback_);
905 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
906 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
907 tracked_objects::ScopedTracker tracking_profile(
908 FROM_HERE_WITH_EXPLICIT_FUNCTION(
909 "455884 HttpStreamFactoryImpl::Job::DoInitConnectionComplete"));
910 if (IsPreconnecting()) {
911 if (using_quic_)
912 return result;
913 DCHECK_EQ(OK, result);
914 return OK;
917 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
918 // We found a SPDY connection after resolving the host. This is
919 // probably an IP pooled connection.
920 SpdySessionKey spdy_session_key = GetSpdySessionKey();
921 existing_spdy_session_ =
922 session_->spdy_session_pool()->FindAvailableSession(
923 spdy_session_key, net_log_);
924 if (existing_spdy_session_) {
925 using_spdy_ = true;
926 next_state_ = STATE_CREATE_STREAM;
927 } else {
928 // It is possible that the spdy session no longer exists.
929 ReturnToStateInitConnection(true /* close connection */);
931 return OK;
934 if (proxy_info_.is_quic() && using_quic_ &&
935 (result == ERR_QUIC_PROTOCOL_ERROR ||
936 result == ERR_QUIC_HANDSHAKE_FAILED)) {
937 using_quic_ = false;
938 return ReconsiderProxyAfterError(result);
941 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
942 // errors, such as ignoring certificate errors for Alternate-Protocol.
943 if (result < 0 && waiting_job_) {
944 waiting_job_->Resume(this);
945 waiting_job_ = NULL;
948 // |result| may be the result of any of the stacked pools. The following
949 // logic is used when determining how to interpret an error.
950 // If |result| < 0:
951 // and connection_->socket() != NULL, then the SSL handshake ran and it
952 // is a potentially recoverable error.
953 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
954 // then the SSL handshake ran with an unrecoverable error.
955 // otherwise, the error came from one of the other pools.
956 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
957 connection_->is_ssl_error());
959 if (ssl_started && (result == OK || IsCertificateError(result))) {
960 if (using_quic_ && result == OK) {
961 was_npn_negotiated_ = true;
962 NextProto protocol_negotiated =
963 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
964 protocol_negotiated_ = protocol_negotiated;
965 } else {
966 SSLClientSocket* ssl_socket =
967 static_cast<SSLClientSocket*>(connection_->socket());
968 if (ssl_socket->WasNpnNegotiated()) {
969 was_npn_negotiated_ = true;
970 std::string proto;
971 SSLClientSocket::NextProtoStatus status =
972 ssl_socket->GetNextProto(&proto);
973 NextProto protocol_negotiated =
974 SSLClientSocket::NextProtoFromString(proto);
975 protocol_negotiated_ = protocol_negotiated;
976 net_log_.AddEvent(
977 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
978 base::Bind(&NetLogHttpStreamProtoCallback,
979 status, &proto));
980 if (ssl_socket->was_spdy_negotiated())
981 SwitchToSpdyMode();
983 if (ShouldForceSpdySSL())
984 SwitchToSpdyMode();
986 } else if (proxy_info_.is_https() && connection_->socket() &&
987 result == OK) {
988 ProxyClientSocket* proxy_socket =
989 static_cast<ProxyClientSocket*>(connection_->socket());
990 if (proxy_socket->IsUsingSpdy()) {
991 was_npn_negotiated_ = true;
992 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
993 SwitchToSpdyMode();
997 // We may be using spdy without SSL
998 if (ShouldForceSpdyWithoutSSL())
999 SwitchToSpdyMode();
1001 if (result == ERR_PROXY_AUTH_REQUESTED ||
1002 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
1003 DCHECK(!ssl_started);
1004 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
1005 // SSL socket, but there was an error before that could happen. This
1006 // puts the in progress HttpProxy socket into |connection_| in order to
1007 // complete the auth (or read the response body). The tunnel restart code
1008 // is careful to remove it before returning control to the rest of this
1009 // class.
1010 connection_.reset(connection_->release_pending_http_proxy_connection());
1011 return result;
1014 if (!ssl_started && result < 0 && original_url_.get()) {
1015 job_status_ = STATUS_BROKEN;
1016 MaybeMarkAlternateProtocolBroken();
1017 return result;
1020 if (using_quic_) {
1021 if (result < 0) {
1022 job_status_ = STATUS_BROKEN;
1023 MaybeMarkAlternateProtocolBroken();
1024 return result;
1026 stream_ = quic_request_.ReleaseStream();
1027 next_state_ = STATE_NONE;
1028 return OK;
1031 if (result < 0 && !ssl_started)
1032 return ReconsiderProxyAfterError(result);
1033 establishing_tunnel_ = false;
1035 if (connection_->socket()) {
1036 LogHttpConnectedMetrics(*connection_);
1038 // We officially have a new connection. Record the type.
1039 if (!connection_->is_reused()) {
1040 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
1041 UpdateConnectionTypeHistograms(type);
1045 // Handle SSL errors below.
1046 if (using_ssl_) {
1047 DCHECK(ssl_started);
1048 if (IsCertificateError(result)) {
1049 if (using_spdy_ && original_url_.get() &&
1050 original_url_->SchemeIs("http")) {
1051 // We ignore certificate errors for http over spdy.
1052 spdy_certificate_error_ = result;
1053 result = OK;
1054 } else {
1055 result = HandleCertificateError(result);
1056 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1057 ReturnToStateInitConnection(true /* close connection */);
1058 return result;
1062 if (result < 0)
1063 return result;
1066 next_state_ = STATE_CREATE_STREAM;
1067 return OK;
1070 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1071 // This state indicates that the stream request is in a partially
1072 // completed state, and we've called back to the delegate for more
1073 // information.
1075 // We're always waiting here for the delegate to call us back.
1076 return ERR_IO_PENDING;
1079 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1080 base::WeakPtr<SpdySession> session, bool direct) {
1081 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1082 // implemented.
1083 if (stream_factory_->for_websockets_)
1084 return ERR_NOT_IMPLEMENTED;
1086 // TODO(willchan): Delete this code, because eventually, the
1087 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1088 // will know when SpdySessions become available.
1090 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1091 stream_.reset(new SpdyHttpStream(session, use_relative_url));
1092 return OK;
1095 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1096 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
1097 tracked_objects::ScopedTracker tracking_profile(
1098 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1099 "455884 HttpStreamFactoryImpl::Job::DoCreateStream"));
1100 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1102 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1104 // We only set the socket motivation if we're the first to use
1105 // this socket. Is there a race for two SPDY requests? We really
1106 // need to plumb this through to the connect level.
1107 if (connection_->socket() && !connection_->is_reused())
1108 SetSocketMotivation();
1110 if (!using_spdy_) {
1111 // We may get ftp scheme when fetching ftp resources through proxy.
1112 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1113 (request_info_.url.SchemeIs("http") ||
1114 request_info_.url.SchemeIs("ftp"));
1115 if (stream_factory_->for_websockets_) {
1116 DCHECK(request_);
1117 DCHECK(request_->websocket_handshake_stream_create_helper());
1118 websocket_stream_.reset(
1119 request_->websocket_handshake_stream_create_helper()
1120 ->CreateBasicStream(connection_.Pass(), using_proxy));
1121 } else {
1122 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1124 return OK;
1127 CHECK(!stream_.get());
1129 bool direct = true;
1130 const ProxyServer& proxy_server = proxy_info_.proxy_server();
1131 PrivacyMode privacy_mode = request_info_.privacy_mode;
1132 if (IsHttpsProxyAndHttpUrl())
1133 direct = false;
1135 if (existing_spdy_session_.get()) {
1136 // We picked up an existing session, so we don't need our socket.
1137 if (connection_->socket())
1138 connection_->socket()->Disconnect();
1139 connection_->Reset();
1141 int set_result = SetSpdyHttpStream(existing_spdy_session_, direct);
1142 existing_spdy_session_.reset();
1143 return set_result;
1146 SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1147 if (IsHttpsProxyAndHttpUrl()) {
1148 // If we don't have a direct SPDY session, and we're using an HTTPS
1149 // proxy, then we might have a SPDY session to the proxy.
1150 // We never use privacy mode for connection to proxy server.
1151 spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1152 ProxyServer::Direct(),
1153 PRIVACY_MODE_DISABLED);
1156 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1157 base::WeakPtr<SpdySession> spdy_session =
1158 spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1160 if (spdy_session) {
1161 return SetSpdyHttpStream(spdy_session, direct);
1164 spdy_session =
1165 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1166 connection_.Pass(),
1167 net_log_,
1168 spdy_certificate_error_,
1169 using_ssl_);
1170 if (!spdy_session->HasAcceptableTransportSecurity()) {
1171 spdy_session->CloseSessionOnError(
1172 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1173 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1176 new_spdy_session_ = spdy_session;
1177 spdy_session_direct_ = direct;
1178 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1179 base::WeakPtr<HttpServerProperties> http_server_properties =
1180 session_->http_server_properties();
1181 if (http_server_properties)
1182 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1184 // Create a SpdyHttpStream attached to the session;
1185 // OnNewSpdySessionReadyCallback is not called until an event loop
1186 // iteration later, so if the SpdySession is closed between then, allow
1187 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1188 // bubble up to the request.
1189 return SetSpdyHttpStream(new_spdy_session_, spdy_session_direct_);
1192 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1193 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
1194 tracked_objects::ScopedTracker tracking_profile(
1195 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1196 "455884 HttpStreamFactoryImpl::Job::DoCreateStreamComplete"));
1197 if (result < 0)
1198 return result;
1200 session_->proxy_service()->ReportSuccess(proxy_info_,
1201 session_->network_delegate());
1202 next_state_ = STATE_NONE;
1203 return OK;
1206 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1207 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
1208 tracked_objects::ScopedTracker tracking_profile(
1209 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1210 "455884 HttpStreamFactoryImpl::Job::DoRestartTunnelAuth"));
1211 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1212 ProxyClientSocket* proxy_socket =
1213 static_cast<ProxyClientSocket*>(connection_->socket());
1214 return proxy_socket->RestartWithAuth(io_callback_);
1217 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1218 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
1219 tracked_objects::ScopedTracker tracking_profile(
1220 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1221 "455884 HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete"));
1222 if (result == ERR_PROXY_AUTH_REQUESTED)
1223 return result;
1225 if (result == OK) {
1226 // Now that we've got the HttpProxyClientSocket connected. We have
1227 // to release it as an idle socket into the pool and start the connection
1228 // process from the beginning. Trying to pass it in with the
1229 // SSLSocketParams might cause a deadlock since params are dispatched
1230 // interchangeably. This request won't necessarily get this http proxy
1231 // socket, but there will be forward progress.
1232 establishing_tunnel_ = false;
1233 ReturnToStateInitConnection(false /* do not close connection */);
1234 return OK;
1237 return ReconsiderProxyAfterError(result);
1240 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1241 bool close_connection) {
1242 if (close_connection && connection_->socket())
1243 connection_->socket()->Disconnect();
1244 connection_->Reset();
1246 if (request_)
1247 request_->RemoveRequestFromSpdySessionRequestMap();
1249 next_state_ = STATE_INIT_CONNECTION;
1252 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1253 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1254 connection_->socket()->SetSubresourceSpeculation();
1255 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1256 connection_->socket()->SetOmniboxSpeculation();
1257 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1260 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1261 if (!proxy_info_.is_https())
1262 return false;
1263 if (original_url_.get()) {
1264 // We currently only support Alternate-Protocol where the original scheme
1265 // is http.
1266 DCHECK(original_url_->SchemeIs("http"));
1267 return original_url_->SchemeIs("http");
1269 return request_info_.url.SchemeIs("http");
1272 // Sets several fields of ssl_config for the given origin_server based on the
1273 // proxy info and other factors.
1274 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1275 const HostPortPair& origin_server,
1276 SSLConfig* ssl_config,
1277 bool is_proxy) const {
1278 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1279 // When connecting through an HTTPS proxy, disable TLS False Start so
1280 // that client authentication errors can be distinguished between those
1281 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1282 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1283 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1284 // TODO(rch): This assumes that the HTTPS proxy will only request a
1285 // client certificate during the initial handshake.
1286 // http://crbug.com/59292
1287 ssl_config->false_start_enabled = false;
1290 enum {
1291 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1292 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1293 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1294 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1295 FALLBACK_MAX
1298 int fallback = FALLBACK_NONE;
1299 if (ssl_config->version_fallback) {
1300 switch (ssl_config->version_max) {
1301 case SSL_PROTOCOL_VERSION_SSL3:
1302 fallback = FALLBACK_SSL3;
1303 break;
1304 case SSL_PROTOCOL_VERSION_TLS1:
1305 fallback = FALLBACK_TLS1;
1306 break;
1307 case SSL_PROTOCOL_VERSION_TLS1_1:
1308 fallback = FALLBACK_TLS1_1;
1309 break;
1312 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1313 fallback, FALLBACK_MAX);
1315 // We also wish to measure the amount of fallback connections for a host that
1316 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1317 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1318 // caused by network middleware rather than buggy HTTPS servers.
1319 const std::string& host = origin_server.host();
1320 if (!is_proxy &&
1321 host.size() >= 10 &&
1322 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1323 (host.size() == 10 || host[host.size()-11] == '.')) {
1324 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1325 fallback, FALLBACK_MAX);
1328 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1329 ssl_config->verify_ev_cert = true;
1331 // Disable Channel ID if privacy mode is enabled.
1332 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1333 ssl_config->channel_id_enabled = false;
1337 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1338 DCHECK(!pac_request_);
1339 DCHECK(session_);
1341 // A failure to resolve the hostname or any error related to establishing a
1342 // TCP connection could be grounds for trying a new proxy configuration.
1344 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1345 // to proxy servers. The hostname in those URLs might fail to resolve if we
1346 // are still using a non-proxy config. We need to check if a proxy config
1347 // now exists that corresponds to a proxy server that could load the URL.
1349 switch (error) {
1350 case ERR_PROXY_CONNECTION_FAILED:
1351 case ERR_NAME_NOT_RESOLVED:
1352 case ERR_INTERNET_DISCONNECTED:
1353 case ERR_ADDRESS_UNREACHABLE:
1354 case ERR_CONNECTION_CLOSED:
1355 case ERR_CONNECTION_TIMED_OUT:
1356 case ERR_CONNECTION_RESET:
1357 case ERR_CONNECTION_REFUSED:
1358 case ERR_CONNECTION_ABORTED:
1359 case ERR_TIMED_OUT:
1360 case ERR_TUNNEL_CONNECTION_FAILED:
1361 case ERR_SOCKS_CONNECTION_FAILED:
1362 // This can happen in the case of trying to talk to a proxy using SSL, and
1363 // ending up talking to a captive portal that supports SSL instead.
1364 case ERR_PROXY_CERTIFICATE_INVALID:
1365 // This can happen when trying to talk SSL to a non-SSL server (Like a
1366 // captive portal).
1367 case ERR_QUIC_PROTOCOL_ERROR:
1368 case ERR_QUIC_HANDSHAKE_FAILED:
1369 case ERR_SSL_PROTOCOL_ERROR:
1370 break;
1371 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1372 // Remap the SOCKS-specific "host unreachable" error to a more
1373 // generic error code (this way consumers like the link doctor
1374 // know to substitute their error page).
1376 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1377 // differentiate between a proxy-side "host not found" versus a proxy-side
1378 // "address unreachable" error, and will report both of these failures as
1379 // ERR_ADDRESS_UNREACHABLE.
1380 return ERR_ADDRESS_UNREACHABLE;
1381 default:
1382 return error;
1385 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1386 return error;
1389 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1390 session_->ssl_client_auth_cache()->Remove(
1391 proxy_info_.proxy_server().host_port_pair());
1394 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1395 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1396 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1397 if (rv == OK || rv == ERR_IO_PENDING) {
1398 // If the error was during connection setup, there is no socket to
1399 // disconnect.
1400 if (connection_->socket())
1401 connection_->socket()->Disconnect();
1402 connection_->Reset();
1403 if (request_)
1404 request_->RemoveRequestFromSpdySessionRequestMap();
1405 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1406 } else {
1407 // If ReconsiderProxyAfterError() failed synchronously, it means
1408 // there was nothing left to fall-back to, so fail the transaction
1409 // with the last connection error we got.
1410 // TODO(eroman): This is a confusing contract, make it more obvious.
1411 rv = error;
1414 return rv;
1417 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1418 DCHECK(using_ssl_);
1419 DCHECK(IsCertificateError(error));
1421 SSLClientSocket* ssl_socket =
1422 static_cast<SSLClientSocket*>(connection_->socket());
1423 ssl_socket->GetSSLInfo(&ssl_info_);
1425 // Add the bad certificate to the set of allowed certificates in the
1426 // SSL config object. This data structure will be consulted after calling
1427 // RestartIgnoringLastError(). And the user will be asked interactively
1428 // before RestartIgnoringLastError() is ever called.
1429 SSLConfig::CertAndStatus bad_cert;
1431 // |ssl_info_.cert| may be NULL if we failed to create
1432 // X509Certificate for whatever reason, but normally it shouldn't
1433 // happen, unless this code is used inside sandbox.
1434 if (ssl_info_.cert.get() == NULL ||
1435 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1436 &bad_cert.der_cert)) {
1437 return error;
1439 bad_cert.cert_status = ssl_info_.cert_status;
1440 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1442 int load_flags = request_info_.load_flags;
1443 if (session_->params().ignore_certificate_errors)
1444 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1445 if (ssl_socket->IgnoreCertError(error, load_flags))
1446 return OK;
1447 return error;
1450 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1451 if (HttpStreamFactory::spdy_enabled())
1452 using_spdy_ = true;
1455 // static
1456 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1457 const ClientSocketHandle& handle) {
1458 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
1459 ClientSocketHandle::NUM_TYPES);
1461 switch (handle.reuse_type()) {
1462 case ClientSocketHandle::UNUSED:
1463 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1464 handle.setup_time(),
1465 base::TimeDelta::FromMilliseconds(1),
1466 base::TimeDelta::FromMinutes(10),
1467 100);
1468 break;
1469 case ClientSocketHandle::UNUSED_IDLE:
1470 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1471 handle.idle_time(),
1472 base::TimeDelta::FromMilliseconds(1),
1473 base::TimeDelta::FromMinutes(6),
1474 100);
1475 break;
1476 case ClientSocketHandle::REUSED_IDLE:
1477 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1478 handle.idle_time(),
1479 base::TimeDelta::FromMilliseconds(1),
1480 base::TimeDelta::FromMinutes(6),
1481 100);
1482 break;
1483 default:
1484 NOTREACHED();
1485 break;
1489 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1490 DCHECK_GE(num_streams_, 0);
1491 return num_streams_ > 0;
1494 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1495 return !IsPreconnecting() && !request_;
1498 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1499 if (using_existing_quic_session_) {
1500 // If an existing session was used, then no TCP connection was
1501 // started.
1502 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE);
1503 } else if (original_url_) {
1504 // This job was the alternate protocol job, and hence won the race.
1505 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE);
1506 } else {
1507 // This job was the normal job, and hence the alternate protocol job lost
1508 // the race.
1509 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE);
1513 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1514 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1515 other_job_status_ = job.job_status_;
1516 other_job_alternate_protocol_ = job.alternate_protocol_;
1517 MaybeMarkAlternateProtocolBroken();
1520 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1521 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1522 return;
1524 bool is_alternate_protocol_job = original_url_.get() != NULL;
1525 if (is_alternate_protocol_job) {
1526 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1527 HistogramBrokenAlternateProtocolLocation(
1528 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1529 session_->http_server_properties()->SetBrokenAlternateProtocol(
1530 HostPortPair::FromURL(*original_url_));
1532 return;
1535 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1536 HistogramBrokenAlternateProtocolLocation(
1537 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1538 session_->http_server_properties()->SetBrokenAlternateProtocol(
1539 HostPortPair::FromURL(request_info_.url));
1543 } // namespace net