Make Ctrl + T from apps focus the new tab's omnibox on Linux and ChromeOS.
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blobb07a461e9b0048a75a9d2c36958c99f6365997cf
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/metrics/histogram_macros.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/values.h"
20 #include "build/build_config.h"
21 #include "net/base/connection_type_histograms.h"
22 #include "net/base/net_util.h"
23 #include "net/http/http_basic_stream.h"
24 #include "net/http/http_network_session.h"
25 #include "net/http/http_proxy_client_socket.h"
26 #include "net/http/http_proxy_client_socket_pool.h"
27 #include "net/http/http_request_info.h"
28 #include "net/http/http_server_properties.h"
29 #include "net/http/http_stream_factory.h"
30 #include "net/http/http_stream_factory_impl_request.h"
31 #include "net/log/net_log.h"
32 #include "net/quic/quic_http_stream.h"
33 #include "net/socket/client_socket_handle.h"
34 #include "net/socket/client_socket_pool.h"
35 #include "net/socket/client_socket_pool_manager.h"
36 #include "net/socket/socks_client_socket_pool.h"
37 #include "net/socket/ssl_client_socket.h"
38 #include "net/socket/ssl_client_socket_pool.h"
39 #include "net/spdy/spdy_http_stream.h"
40 #include "net/spdy/spdy_session.h"
41 #include "net/spdy/spdy_session_pool.h"
42 #include "net/ssl/ssl_cert_request_info.h"
44 namespace net {
46 // Returns parameters associated with the start of a HTTP stream job.
47 base::Value* NetLogHttpStreamJobCallback(
48 const GURL* original_url,
49 const GURL* url,
50 const AlternativeService* alternative_service,
51 RequestPriority priority,
52 NetLogCaptureMode /* capture_mode */) {
53 base::DictionaryValue* dict = new base::DictionaryValue();
54 dict->SetString("original_url", original_url->GetOrigin().spec());
55 dict->SetString("url", url->GetOrigin().spec());
56 dict->SetString("alternative_service", alternative_service->ToString());
57 dict->SetString("priority", RequestPriorityToString(priority));
58 return dict;
61 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
62 // stream.
63 base::Value* NetLogHttpStreamProtoCallback(
64 const SSLClientSocket::NextProtoStatus status,
65 const std::string* proto,
66 NetLogCaptureMode /* capture_mode */) {
67 base::DictionaryValue* dict = new base::DictionaryValue();
69 dict->SetString("next_proto_status",
70 SSLClientSocket::NextProtoStatusToString(status));
71 dict->SetString("proto", *proto);
72 return dict;
75 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
76 HttpNetworkSession* session,
77 const HttpRequestInfo& request_info,
78 RequestPriority priority,
79 const SSLConfig& server_ssl_config,
80 const SSLConfig& proxy_ssl_config,
81 NetLog* net_log)
82 : request_(NULL),
83 request_info_(request_info),
84 priority_(priority),
85 server_ssl_config_(server_ssl_config),
86 proxy_ssl_config_(proxy_ssl_config),
87 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
88 io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
89 connection_(new ClientSocketHandle),
90 session_(session),
91 stream_factory_(stream_factory),
92 next_state_(STATE_NONE),
93 pac_request_(NULL),
94 blocking_job_(NULL),
95 waiting_job_(NULL),
96 using_ssl_(false),
97 using_spdy_(false),
98 using_quic_(false),
99 quic_request_(session_->quic_stream_factory()),
100 using_existing_quic_session_(false),
101 spdy_certificate_error_(OK),
102 establishing_tunnel_(false),
103 was_npn_negotiated_(false),
104 protocol_negotiated_(kProtoUnknown),
105 num_streams_(0),
106 spdy_session_direct_(false),
107 job_status_(STATUS_RUNNING),
108 other_job_status_(STATUS_RUNNING),
109 ptr_factory_(this) {
110 DCHECK(stream_factory);
111 DCHECK(session);
114 HttpStreamFactoryImpl::Job::~Job() {
115 net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
117 // When we're in a partially constructed state, waiting for the user to
118 // provide certificate handling information or authentication, we can't reuse
119 // this stream at all.
120 if (next_state_ == STATE_WAITING_USER_ACTION) {
121 connection_->socket()->Disconnect();
122 connection_.reset();
125 if (pac_request_)
126 session_->proxy_service()->CancelPacRequest(pac_request_);
128 // The stream could be in a partial state. It is not reusable.
129 if (stream_.get() && next_state_ != STATE_DONE)
130 stream_->Close(true /* not reusable */);
133 void HttpStreamFactoryImpl::Job::Start(Request* request) {
134 DCHECK(request);
135 request_ = request;
136 StartInternal();
139 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
140 DCHECK_GT(num_streams, 0);
141 base::WeakPtr<HttpServerProperties> http_server_properties =
142 session_->http_server_properties();
143 if (http_server_properties &&
144 http_server_properties->SupportsRequestPriority(
145 HostPortPair::FromURL(request_info_.url))) {
146 num_streams_ = 1;
147 } else {
148 num_streams_ = num_streams;
150 return StartInternal();
153 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
154 const AuthCredentials& credentials) {
155 DCHECK(establishing_tunnel_);
156 next_state_ = STATE_RESTART_TUNNEL_AUTH;
157 stream_.reset();
158 return RunLoop(OK);
161 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
162 switch (next_state_) {
163 case STATE_RESOLVE_PROXY_COMPLETE:
164 return session_->proxy_service()->GetLoadState(pac_request_);
165 case STATE_INIT_CONNECTION_COMPLETE:
166 case STATE_CREATE_STREAM_COMPLETE:
167 return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
168 default:
169 return LOAD_STATE_IDLE;
173 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
174 AlternativeService alternative_service) {
175 DCHECK(!IsAlternate());
176 alternative_service_ = alternative_service;
177 if (alternative_service.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 if (IsHttpsProxyAndHttpUrl()) {
275 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
276 ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
278 return SpdySessionKey(server_, proxy_info_.proxy_server(),
279 request_info_.privacy_mode);
282 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
283 // We need to make sure that if a spdy session was created for
284 // https://somehost/ that we don't use that session for http://somehost:443/.
285 // The only time we can use an existing session is if the request URL is
286 // https (the normal case) or if we're connection to a SPDY proxy.
287 // https://crbug.com/133176
288 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
289 // working.
290 return origin_url_.SchemeIs("https") ||
291 proxy_info_.proxy_server().is_https() || IsSpdyAlternate();
294 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
295 DCHECK(stream_.get());
296 DCHECK(!IsPreconnecting());
297 DCHECK(!stream_factory_->for_websockets_);
299 MaybeCopyConnectionAttemptsFromClientSocketHandleToRequest();
301 if (IsOrphaned()) {
302 stream_factory_->OnOrphanedJobComplete(this);
303 } else {
304 request_->Complete(was_npn_negotiated(),
305 protocol_negotiated(),
306 using_spdy(),
307 net_log_);
308 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
309 stream_.release());
311 // |this| may be deleted after this call.
314 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
315 DCHECK(websocket_stream_);
316 DCHECK(!IsPreconnecting());
317 DCHECK(stream_factory_->for_websockets_);
318 // An orphaned WebSocket job will be closed immediately and
319 // never be ready.
320 DCHECK(!IsOrphaned());
322 MaybeCopyConnectionAttemptsFromClientSocketHandleToRequest();
324 request_->Complete(was_npn_negotiated(),
325 protocol_negotiated(),
326 using_spdy(),
327 net_log_);
328 request_->OnWebSocketHandshakeStreamReady(this,
329 server_ssl_config_,
330 proxy_info_,
331 websocket_stream_.release());
332 // |this| may be deleted after this call.
335 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
336 DCHECK(stream_.get());
337 DCHECK(!IsPreconnecting());
338 DCHECK(using_spdy());
339 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
340 // NULL at this point if the SpdySession closed immediately after creation.
341 base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
342 new_spdy_session_.reset();
344 MaybeCopyConnectionAttemptsFromClientSocketHandleToRequest();
346 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
347 // rather than notifying |request_| directly.
348 if (IsOrphaned()) {
349 if (spdy_session) {
350 stream_factory_->OnNewSpdySessionReady(
351 spdy_session, spdy_session_direct_, server_ssl_config_, proxy_info_,
352 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_);
354 stream_factory_->OnOrphanedJobComplete(this);
355 } else {
356 request_->OnNewSpdySessionReady(
357 this, stream_.Pass(), spdy_session, spdy_session_direct_);
359 // |this| may be deleted after this call.
362 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result) {
363 DCHECK(!IsPreconnecting());
365 MaybeCopyConnectionAttemptsFromClientSocketHandleToRequest();
367 if (IsOrphaned())
368 stream_factory_->OnOrphanedJobComplete(this);
369 else
370 request_->OnStreamFailed(this, result, server_ssl_config_);
371 // |this| may be deleted after this call.
374 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
375 int result, const SSLInfo& ssl_info) {
376 DCHECK(!IsPreconnecting());
378 MaybeCopyConnectionAttemptsFromClientSocketHandleToRequest();
380 if (IsOrphaned())
381 stream_factory_->OnOrphanedJobComplete(this);
382 else
383 request_->OnCertificateError(this, result, server_ssl_config_, ssl_info);
384 // |this| may be deleted after this call.
387 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
388 const HttpResponseInfo& response,
389 HttpAuthController* auth_controller) {
390 DCHECK(!IsPreconnecting());
391 if (IsOrphaned())
392 stream_factory_->OnOrphanedJobComplete(this);
393 else
394 request_->OnNeedsProxyAuth(
395 this, response, server_ssl_config_, proxy_info_, auth_controller);
396 // |this| may be deleted after this call.
399 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
400 SSLCertRequestInfo* cert_info) {
401 DCHECK(!IsPreconnecting());
402 if (IsOrphaned())
403 stream_factory_->OnOrphanedJobComplete(this);
404 else
405 request_->OnNeedsClientAuth(this, server_ssl_config_, cert_info);
406 // |this| may be deleted after this call.
409 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
410 const HttpResponseInfo& response_info,
411 HttpStream* stream) {
412 DCHECK(!IsPreconnecting());
413 if (IsOrphaned())
414 stream_factory_->OnOrphanedJobComplete(this);
415 else
416 request_->OnHttpsProxyTunnelResponse(
417 this, response_info, server_ssl_config_, proxy_info_, stream);
418 // |this| may be deleted after this call.
421 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
422 DCHECK(!request_);
423 if (new_spdy_session_.get()) {
424 stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
425 spdy_session_direct_,
426 server_ssl_config_,
427 proxy_info_,
428 was_npn_negotiated(),
429 protocol_negotiated(),
430 using_spdy(),
431 net_log_);
433 stream_factory_->OnPreconnectsComplete(this);
434 // |this| may be deleted after this call.
437 // static
438 int HttpStreamFactoryImpl::Job::OnHostResolution(
439 SpdySessionPool* spdy_session_pool,
440 const SpdySessionKey& spdy_session_key,
441 const AddressList& addresses,
442 const BoundNetLog& net_log) {
443 // It is OK to dereference spdy_session_pool, because the
444 // ClientSocketPoolManager will be destroyed in the same callback that
445 // destroys the SpdySessionPool.
446 return
447 spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
448 ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
451 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
452 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
453 tracked_objects::ScopedTracker tracking_profile(
454 FROM_HERE_WITH_EXPLICIT_FUNCTION(
455 "455884 HttpStreamFactoryImpl::Job::OnIOComplete"));
456 RunLoop(result);
459 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
460 result = DoLoop(result);
462 if (result == ERR_IO_PENDING)
463 return result;
465 // If there was an error, we should have already resumed the |waiting_job_|,
466 // if there was one.
467 DCHECK(result == OK || waiting_job_ == NULL);
469 if (IsPreconnecting()) {
470 base::MessageLoop::current()->PostTask(
471 FROM_HERE,
472 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
473 ptr_factory_.GetWeakPtr()));
474 return ERR_IO_PENDING;
477 if (IsCertificateError(result)) {
478 // Retrieve SSL information from the socket.
479 GetSSLInfo();
481 next_state_ = STATE_WAITING_USER_ACTION;
482 base::MessageLoop::current()->PostTask(
483 FROM_HERE,
484 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
485 ptr_factory_.GetWeakPtr(), result, ssl_info_));
486 return ERR_IO_PENDING;
489 switch (result) {
490 case ERR_PROXY_AUTH_REQUESTED: {
491 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
492 connection_.get() != NULL);
493 if (!connection_.get())
494 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
495 CHECK(connection_->socket());
496 CHECK(establishing_tunnel_);
498 next_state_ = STATE_WAITING_USER_ACTION;
499 ProxyClientSocket* proxy_socket =
500 static_cast<ProxyClientSocket*>(connection_->socket());
501 base::MessageLoop::current()->PostTask(
502 FROM_HERE,
503 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
504 *proxy_socket->GetConnectResponseInfo(),
505 proxy_socket->GetAuthController()));
506 return ERR_IO_PENDING;
509 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
510 base::MessageLoop::current()->PostTask(
511 FROM_HERE,
512 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
513 connection_->ssl_error_response_info().cert_request_info));
514 return ERR_IO_PENDING;
516 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
517 DCHECK(connection_.get());
518 DCHECK(connection_->socket());
519 DCHECK(establishing_tunnel_);
521 ProxyClientSocket* proxy_socket =
522 static_cast<ProxyClientSocket*>(connection_->socket());
523 base::MessageLoop::current()->PostTask(
524 FROM_HERE,
525 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
526 ptr_factory_.GetWeakPtr(),
527 *proxy_socket->GetConnectResponseInfo(),
528 proxy_socket->CreateConnectResponseStream()));
529 return ERR_IO_PENDING;
532 case OK:
533 job_status_ = STATUS_SUCCEEDED;
534 MaybeMarkAlternativeServiceBroken();
535 next_state_ = STATE_DONE;
536 if (new_spdy_session_.get()) {
537 base::MessageLoop::current()->PostTask(
538 FROM_HERE,
539 base::Bind(&Job::OnNewSpdySessionReadyCallback,
540 ptr_factory_.GetWeakPtr()));
541 } else if (stream_factory_->for_websockets_) {
542 DCHECK(websocket_stream_);
543 base::MessageLoop::current()->PostTask(
544 FROM_HERE,
545 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
546 ptr_factory_.GetWeakPtr()));
547 } else {
548 DCHECK(stream_.get());
549 base::MessageLoop::current()->PostTask(
550 FROM_HERE,
551 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
553 return ERR_IO_PENDING;
555 default:
556 DCHECK(result != ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN ||
557 IsSpdyAlternate());
558 if (job_status_ != STATUS_BROKEN) {
559 DCHECK_EQ(STATUS_RUNNING, job_status_);
560 job_status_ = STATUS_FAILED;
561 // TODO(bnc): If (result == ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN),
562 // then instead of marking alternative service broken, mark (origin,
563 // alternative service) couple as invalid.
564 MaybeMarkAlternativeServiceBroken();
566 base::MessageLoop::current()->PostTask(
567 FROM_HERE,
568 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
569 result));
570 return ERR_IO_PENDING;
574 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
575 DCHECK_NE(next_state_, STATE_NONE);
576 int rv = result;
577 do {
578 State state = next_state_;
579 next_state_ = STATE_NONE;
580 switch (state) {
581 case STATE_START:
582 DCHECK_EQ(OK, rv);
583 rv = DoStart();
584 break;
585 case STATE_RESOLVE_PROXY:
586 DCHECK_EQ(OK, rv);
587 rv = DoResolveProxy();
588 break;
589 case STATE_RESOLVE_PROXY_COMPLETE:
590 rv = DoResolveProxyComplete(rv);
591 break;
592 case STATE_WAIT_FOR_JOB:
593 DCHECK_EQ(OK, rv);
594 rv = DoWaitForJob();
595 break;
596 case STATE_WAIT_FOR_JOB_COMPLETE:
597 rv = DoWaitForJobComplete(rv);
598 break;
599 case STATE_INIT_CONNECTION:
600 DCHECK_EQ(OK, rv);
601 rv = DoInitConnection();
602 break;
603 case STATE_INIT_CONNECTION_COMPLETE:
604 rv = DoInitConnectionComplete(rv);
605 break;
606 case STATE_WAITING_USER_ACTION:
607 rv = DoWaitingUserAction(rv);
608 break;
609 case STATE_RESTART_TUNNEL_AUTH:
610 DCHECK_EQ(OK, rv);
611 rv = DoRestartTunnelAuth();
612 break;
613 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
614 rv = DoRestartTunnelAuthComplete(rv);
615 break;
616 case STATE_CREATE_STREAM:
617 DCHECK_EQ(OK, rv);
618 rv = DoCreateStream();
619 break;
620 case STATE_CREATE_STREAM_COMPLETE:
621 rv = DoCreateStreamComplete(rv);
622 break;
623 default:
624 NOTREACHED() << "bad state";
625 rv = ERR_FAILED;
626 break;
628 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
629 return rv;
632 int HttpStreamFactoryImpl::Job::StartInternal() {
633 CHECK_EQ(STATE_NONE, next_state_);
634 next_state_ = STATE_START;
635 int rv = RunLoop(OK);
636 DCHECK_EQ(ERR_IO_PENDING, rv);
637 return rv;
640 int HttpStreamFactoryImpl::Job::DoStart() {
641 if (IsAlternate()) {
642 server_ = alternative_service_.host_port_pair();
643 } else {
644 server_ = HostPortPair::FromURL(request_info_.url);
646 origin_url_ =
647 stream_factory_->ApplyHostMappingRules(request_info_.url, &server_);
648 valid_spdy_session_pool_.reset(new ValidSpdySessionPool(
649 session_->spdy_session_pool(), origin_url_, IsSpdyAlternate()));
651 net_log_.BeginEvent(
652 NetLog::TYPE_HTTP_STREAM_JOB,
653 base::Bind(&NetLogHttpStreamJobCallback, &request_info_.url, &origin_url_,
654 &alternative_service_, priority_));
656 // Don't connect to restricted ports.
657 bool is_port_allowed = IsPortAllowedByDefault(server_.port());
658 if (request_info_.url.SchemeIs("ftp")) {
659 // Never share connection with other jobs for FTP requests.
660 DCHECK(!waiting_job_);
662 is_port_allowed = IsPortAllowedByFtp(server_.port());
664 if (!is_port_allowed && !IsPortAllowedByOverride(server_.port())) {
665 if (waiting_job_) {
666 waiting_job_->Resume(this);
667 waiting_job_ = NULL;
669 return ERR_UNSAFE_PORT;
672 next_state_ = STATE_RESOLVE_PROXY;
673 return OK;
676 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
677 DCHECK(!pac_request_);
678 DCHECK(session_);
680 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
682 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
683 proxy_info_.UseDirect();
684 return OK;
687 // TODO(rch): remove this code since Alt-Svc seems to prohibit it.
688 GURL url_for_proxy = origin_url_;
689 // For SPDY via Alt-Svc, set |alternative_service_url_| to
690 // https://<alternative host>:<alternative port>/...
691 // so the proxy resolution works with the actual destination, and so
692 // that the correct socket pool is used.
693 if (IsSpdyAlternate()) {
694 // TODO(rch): Figure out how to make QUIC iteract with PAC
695 // scripts. By not re-writing the URL, we will query the PAC script
696 // for the proxy to use to reach the original URL via TCP. But
697 // the alternate request will be going via UDP to a different port.
698 GURL::Replacements replacements;
699 // new_port needs to be in scope here because GURL::Replacements references
700 // the memory contained by it directly.
701 const std::string new_port = base::IntToString(alternative_service_.port);
702 replacements.SetSchemeStr("https");
703 replacements.SetPortStr(new_port);
704 url_for_proxy = url_for_proxy.ReplaceComponents(replacements);
707 return session_->proxy_service()->ResolveProxy(
708 url_for_proxy, request_info_.load_flags, &proxy_info_, io_callback_,
709 &pac_request_, session_->network_delegate(), net_log_);
712 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
713 pac_request_ = NULL;
715 if (result == OK) {
716 // Remove unsupported proxies from the list.
717 int supported_proxies =
718 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP |
719 ProxyServer::SCHEME_HTTPS | ProxyServer::SCHEME_SOCKS4 |
720 ProxyServer::SCHEME_SOCKS5;
722 if (session_->params().enable_quic_for_proxies)
723 supported_proxies |= ProxyServer::SCHEME_QUIC;
725 proxy_info_.RemoveProxiesWithoutScheme(supported_proxies);
727 if (proxy_info_.is_empty()) {
728 // No proxies/direct to choose from. This happens when we don't support
729 // any of the proxies in the returned list.
730 result = ERR_NO_SUPPORTED_PROXIES;
731 } else if (using_quic_ &&
732 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
733 // QUIC can not be spoken to non-QUIC proxies. This error should not be
734 // user visible, because the non-alternate job should be resumed.
735 result = ERR_NO_SUPPORTED_PROXIES;
739 if (result != OK) {
740 if (waiting_job_) {
741 waiting_job_->Resume(this);
742 waiting_job_ = NULL;
744 return result;
747 if (blocking_job_)
748 next_state_ = STATE_WAIT_FOR_JOB;
749 else
750 next_state_ = STATE_INIT_CONNECTION;
751 return OK;
754 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
755 return session_->params().enable_quic &&
756 session_->params().origin_to_force_quic_on.Equals(server_) &&
757 proxy_info_.is_direct();
760 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
761 DCHECK(blocking_job_);
762 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
763 return ERR_IO_PENDING;
766 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
767 DCHECK(!blocking_job_);
768 DCHECK_EQ(OK, result);
769 next_state_ = STATE_INIT_CONNECTION;
770 return OK;
773 int HttpStreamFactoryImpl::Job::DoInitConnection() {
774 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462812 is fixed.
775 tracked_objects::ScopedTracker tracking_profile(
776 FROM_HERE_WITH_EXPLICIT_FUNCTION(
777 "462812 HttpStreamFactoryImpl::Job::DoInitConnection"));
778 DCHECK(!blocking_job_);
779 DCHECK(!connection_->is_initialized());
780 DCHECK(proxy_info_.proxy_server().is_valid());
781 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
783 using_ssl_ = origin_url_.SchemeIs("https") || origin_url_.SchemeIs("wss") ||
784 IsSpdyAlternate();
785 using_spdy_ = false;
787 if (ShouldForceQuic())
788 using_quic_ = true;
790 DCHECK(!using_quic_ || session_->params().enable_quic);
792 if (proxy_info_.is_quic()) {
793 using_quic_ = true;
794 DCHECK(session_->params().enable_quic_for_proxies);
797 if (using_quic_) {
798 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
799 NOTREACHED();
800 // TODO(rch): support QUIC proxies for HTTPS urls.
801 return ERR_NOT_IMPLEMENTED;
803 HostPortPair destination = proxy_info_.is_quic()
804 ? proxy_info_.proxy_server().host_port_pair()
805 : server_;
806 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
807 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
808 int rv = quic_request_.Request(
809 destination, secure_quic, request_info_.privacy_mode,
810 request_info_.method, net_log_, io_callback_);
811 if (rv == OK) {
812 using_existing_quic_session_ = true;
813 } else {
814 // OK, there's no available QUIC session. Let |waiting_job_| resume
815 // if it's paused.
816 if (waiting_job_) {
817 waiting_job_->Resume(this);
818 waiting_job_ = NULL;
821 return rv;
824 SpdySessionKey spdy_session_key = GetSpdySessionKey();
826 // Check first if we have a spdy session for this group. If so, then go
827 // straight to using that.
828 if (CanUseExistingSpdySession()) {
829 base::WeakPtr<SpdySession> spdy_session;
830 int result = valid_spdy_session_pool_->FindAvailableSession(
831 spdy_session_key, net_log_, &spdy_session);
832 if (result != OK)
833 return result;
834 if (spdy_session) {
835 // If we're preconnecting, but we already have a SpdySession, we don't
836 // actually need to preconnect any sockets, so we're done.
837 if (IsPreconnecting())
838 return OK;
839 using_spdy_ = true;
840 next_state_ = STATE_CREATE_STREAM;
841 existing_spdy_session_ = spdy_session;
842 return OK;
845 if (request_ && !request_->HasSpdySessionKey() && using_ssl_) {
846 // Update the spdy session key for the request that launched this job.
847 request_->SetSpdySessionKey(spdy_session_key);
850 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
851 // paused.
852 if (waiting_job_) {
853 waiting_job_->Resume(this);
854 waiting_job_ = NULL;
857 if (proxy_info_.is_http() || proxy_info_.is_https())
858 establishing_tunnel_ = using_ssl_;
860 // TODO(bnc): s/want_spdy_over_npn/expect_spdy_over_npn/
861 bool want_spdy_over_npn = IsAlternate();
863 if (proxy_info_.is_https()) {
864 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
865 &proxy_ssl_config_,
866 true /* is a proxy server */);
867 // Disable revocation checking for HTTPS proxies since the revocation
868 // requests are probably going to need to go through the proxy too.
869 proxy_ssl_config_.rev_checking_enabled = false;
871 if (using_ssl_) {
872 InitSSLConfig(server_, &server_ssl_config_, false /* not a proxy server */);
875 base::WeakPtr<HttpServerProperties> http_server_properties =
876 session_->http_server_properties();
877 if (http_server_properties) {
878 http_server_properties->MaybeForceHTTP11(server_, &server_ssl_config_);
879 if (proxy_info_.is_http() || proxy_info_.is_https()) {
880 http_server_properties->MaybeForceHTTP11(
881 proxy_info_.proxy_server().host_port_pair(), &proxy_ssl_config_);
885 if (IsPreconnecting()) {
886 DCHECK(!stream_factory_->for_websockets_);
887 return PreconnectSocketsForHttpRequest(
888 GetSocketGroup(), server_, request_info_.extra_headers,
889 request_info_.load_flags, priority_, session_, proxy_info_,
890 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
891 request_info_.privacy_mode, net_log_, num_streams_);
894 // If we can't use a SPDY session, don't bother checking for one after
895 // the hostname is resolved.
896 OnHostResolutionCallback resolution_callback =
897 CanUseExistingSpdySession()
898 ? base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
899 spdy_session_key)
900 : OnHostResolutionCallback();
901 if (stream_factory_->for_websockets_) {
902 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
903 SSLConfig websocket_server_ssl_config = server_ssl_config_;
904 websocket_server_ssl_config.next_protos.clear();
905 return InitSocketHandleForWebSocketRequest(
906 GetSocketGroup(), server_, request_info_.extra_headers,
907 request_info_.load_flags, priority_, session_, proxy_info_,
908 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
909 request_info_.privacy_mode, net_log_, connection_.get(),
910 resolution_callback, io_callback_);
913 return InitSocketHandleForHttpRequest(
914 GetSocketGroup(), server_, request_info_.extra_headers,
915 request_info_.load_flags, priority_, session_, proxy_info_,
916 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
917 request_info_.privacy_mode, net_log_, connection_.get(),
918 resolution_callback, io_callback_);
921 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
922 if (IsPreconnecting()) {
923 if (using_quic_)
924 return result;
925 DCHECK_EQ(OK, result);
926 return OK;
929 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
930 // We found a SPDY connection after resolving the host. This is
931 // probably an IP pooled connection.
932 SpdySessionKey spdy_session_key = GetSpdySessionKey();
933 existing_spdy_session_ =
934 session_->spdy_session_pool()->FindAvailableSession(
935 spdy_session_key, net_log_);
936 if (existing_spdy_session_) {
937 using_spdy_ = true;
938 next_state_ = STATE_CREATE_STREAM;
939 } else {
940 // It is possible that the spdy session no longer exists.
941 ReturnToStateInitConnection(true /* close connection */);
943 return OK;
946 if (proxy_info_.is_quic() && using_quic_ &&
947 (result == ERR_QUIC_PROTOCOL_ERROR ||
948 result == ERR_QUIC_HANDSHAKE_FAILED)) {
949 using_quic_ = false;
950 return ReconsiderProxyAfterError(result);
953 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
954 // errors, such as ignoring certificate errors for Alternate-Protocol.
955 if (result < 0 && waiting_job_) {
956 waiting_job_->Resume(this);
957 waiting_job_ = NULL;
960 // |result| may be the result of any of the stacked pools. The following
961 // logic is used when determining how to interpret an error.
962 // If |result| < 0:
963 // and connection_->socket() != NULL, then the SSL handshake ran and it
964 // is a potentially recoverable error.
965 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
966 // then the SSL handshake ran with an unrecoverable error.
967 // otherwise, the error came from one of the other pools.
968 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
969 connection_->is_ssl_error());
971 if (ssl_started && (result == OK || IsCertificateError(result))) {
972 if (using_quic_ && result == OK) {
973 was_npn_negotiated_ = true;
974 protocol_negotiated_ =
975 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
976 } else {
977 SSLClientSocket* ssl_socket =
978 static_cast<SSLClientSocket*>(connection_->socket());
979 if (ssl_socket->WasNpnNegotiated()) {
980 was_npn_negotiated_ = true;
981 std::string proto;
982 SSLClientSocket::NextProtoStatus status =
983 ssl_socket->GetNextProto(&proto);
984 protocol_negotiated_ = SSLClientSocket::NextProtoFromString(proto);
985 net_log_.AddEvent(
986 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
987 base::Bind(&NetLogHttpStreamProtoCallback,
988 status, &proto));
989 if (NextProtoIsSPDY(protocol_negotiated_))
990 SwitchToSpdyMode();
993 } else if (proxy_info_.is_https() && connection_->socket() &&
994 result == OK) {
995 ProxyClientSocket* proxy_socket =
996 static_cast<ProxyClientSocket*>(connection_->socket());
997 if (proxy_socket->IsUsingSpdy()) {
998 was_npn_negotiated_ = true;
999 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
1000 SwitchToSpdyMode();
1004 if (result == ERR_PROXY_AUTH_REQUESTED ||
1005 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
1006 DCHECK(!ssl_started);
1007 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
1008 // SSL socket, but there was an error before that could happen. This
1009 // puts the in progress HttpProxy socket into |connection_| in order to
1010 // complete the auth (or read the response body). The tunnel restart code
1011 // is careful to remove it before returning control to the rest of this
1012 // class.
1013 connection_.reset(connection_->release_pending_http_proxy_connection());
1014 return result;
1017 if (!ssl_started && result < 0 && IsAlternate()) {
1018 job_status_ = STATUS_BROKEN;
1019 // TODO(bnc): if (result == ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN), then
1020 // instead of marking alternative service broken, mark (origin, alternative
1021 // service) couple as invalid.
1022 MaybeMarkAlternativeServiceBroken();
1023 return result;
1026 if (using_quic_) {
1027 if (result < 0) {
1028 job_status_ = STATUS_BROKEN;
1029 MaybeMarkAlternativeServiceBroken();
1030 return result;
1032 stream_ = quic_request_.ReleaseStream();
1033 next_state_ = STATE_NONE;
1034 return OK;
1037 if (result < 0 && !ssl_started)
1038 return ReconsiderProxyAfterError(result);
1039 establishing_tunnel_ = false;
1041 if (connection_->socket()) {
1042 // We officially have a new connection. Record the type.
1043 if (!connection_->is_reused()) {
1044 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
1045 UpdateConnectionTypeHistograms(type);
1049 // Handle SSL errors below.
1050 if (using_ssl_) {
1051 DCHECK(ssl_started);
1052 if (IsCertificateError(result)) {
1053 if (using_spdy_ && IsAlternate() && origin_url_.SchemeIs("http")) {
1054 // We ignore certificate errors for http over spdy.
1055 spdy_certificate_error_ = result;
1056 result = OK;
1057 } else {
1058 result = HandleCertificateError(result);
1059 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1060 ReturnToStateInitConnection(true /* close connection */);
1061 return result;
1065 if (result < 0)
1066 return result;
1069 next_state_ = STATE_CREATE_STREAM;
1070 return OK;
1073 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1074 // This state indicates that the stream request is in a partially
1075 // completed state, and we've called back to the delegate for more
1076 // information.
1078 // We're always waiting here for the delegate to call us back.
1079 return ERR_IO_PENDING;
1082 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1083 base::WeakPtr<SpdySession> session, bool direct) {
1084 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1085 // implemented.
1086 if (stream_factory_->for_websockets_)
1087 return ERR_NOT_IMPLEMENTED;
1089 // TODO(willchan): Delete this code, because eventually, the
1090 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1091 // will know when SpdySessions become available.
1093 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1094 stream_.reset(new SpdyHttpStream(session, use_relative_url));
1095 return OK;
1098 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1099 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462811 is fixed.
1100 tracked_objects::ScopedTracker tracking_profile(
1101 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1102 "462811 HttpStreamFactoryImpl::Job::DoCreateStream"));
1103 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1105 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1107 // We only set the socket motivation if we're the first to use
1108 // this socket. Is there a race for two SPDY requests? We really
1109 // need to plumb this through to the connect level.
1110 if (connection_->socket() && !connection_->is_reused())
1111 SetSocketMotivation();
1113 if (!using_spdy_) {
1114 // We may get ftp scheme when fetching ftp resources through proxy.
1115 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1116 (request_info_.url.SchemeIs("http") ||
1117 request_info_.url.SchemeIs("ftp"));
1118 if (stream_factory_->for_websockets_) {
1119 DCHECK(request_);
1120 DCHECK(request_->websocket_handshake_stream_create_helper());
1121 websocket_stream_.reset(
1122 request_->websocket_handshake_stream_create_helper()
1123 ->CreateBasicStream(connection_.Pass(), using_proxy));
1124 } else {
1125 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1127 return OK;
1130 CHECK(!stream_.get());
1132 bool direct = !IsHttpsProxyAndHttpUrl();
1133 if (existing_spdy_session_.get()) {
1134 // We picked up an existing session, so we don't need our socket.
1135 if (connection_->socket())
1136 connection_->socket()->Disconnect();
1137 connection_->Reset();
1139 int set_result = SetSpdyHttpStream(existing_spdy_session_, direct);
1140 existing_spdy_session_.reset();
1141 return set_result;
1144 SpdySessionKey spdy_session_key = GetSpdySessionKey();
1145 base::WeakPtr<SpdySession> spdy_session;
1146 int result = valid_spdy_session_pool_->FindAvailableSession(
1147 spdy_session_key, net_log_, &spdy_session);
1148 if (result != OK) {
1149 return result;
1151 if (spdy_session) {
1152 return SetSpdyHttpStream(spdy_session, direct);
1155 result = valid_spdy_session_pool_->CreateAvailableSessionFromSocket(
1156 spdy_session_key, connection_.Pass(), net_log_, spdy_certificate_error_,
1157 using_ssl_, &spdy_session);
1158 if (result != OK) {
1159 return result;
1162 if (!spdy_session->HasAcceptableTransportSecurity()) {
1163 spdy_session->CloseSessionOnError(
1164 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1165 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1168 new_spdy_session_ = spdy_session;
1169 spdy_session_direct_ = direct;
1170 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1171 base::WeakPtr<HttpServerProperties> http_server_properties =
1172 session_->http_server_properties();
1173 if (http_server_properties)
1174 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1176 // Create a SpdyHttpStream attached to the session;
1177 // OnNewSpdySessionReadyCallback is not called until an event loop
1178 // iteration later, so if the SpdySession is closed between then, allow
1179 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1180 // bubble up to the request.
1181 return SetSpdyHttpStream(new_spdy_session_, spdy_session_direct_);
1184 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1185 if (result < 0)
1186 return result;
1188 session_->proxy_service()->ReportSuccess(proxy_info_,
1189 session_->network_delegate());
1190 next_state_ = STATE_NONE;
1191 return OK;
1194 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1195 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1196 ProxyClientSocket* proxy_socket =
1197 static_cast<ProxyClientSocket*>(connection_->socket());
1198 return proxy_socket->RestartWithAuth(io_callback_);
1201 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1202 if (result == ERR_PROXY_AUTH_REQUESTED)
1203 return result;
1205 if (result == OK) {
1206 // Now that we've got the HttpProxyClientSocket connected. We have
1207 // to release it as an idle socket into the pool and start the connection
1208 // process from the beginning. Trying to pass it in with the
1209 // SSLSocketParams might cause a deadlock since params are dispatched
1210 // interchangeably. This request won't necessarily get this http proxy
1211 // socket, but there will be forward progress.
1212 establishing_tunnel_ = false;
1213 ReturnToStateInitConnection(false /* do not close connection */);
1214 return OK;
1217 return ReconsiderProxyAfterError(result);
1220 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1221 bool close_connection) {
1222 if (close_connection && connection_->socket())
1223 connection_->socket()->Disconnect();
1224 connection_->Reset();
1226 if (request_)
1227 request_->RemoveRequestFromSpdySessionRequestMap();
1229 next_state_ = STATE_INIT_CONNECTION;
1232 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1233 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1234 connection_->socket()->SetSubresourceSpeculation();
1235 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1236 connection_->socket()->SetOmniboxSpeculation();
1237 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1240 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1241 if (!proxy_info_.is_https())
1242 return false;
1243 if (IsAlternate()) {
1244 // We currently only support Alternate-Protocol where the original scheme
1245 // is http.
1246 DCHECK(origin_url_.SchemeIs("http"));
1247 return origin_url_.SchemeIs("http");
1249 return request_info_.url.SchemeIs("http");
1252 bool HttpStreamFactoryImpl::Job::IsAlternate() const {
1253 return alternative_service_.protocol != UNINITIALIZED_ALTERNATE_PROTOCOL;
1256 bool HttpStreamFactoryImpl::Job::IsSpdyAlternate() const {
1257 return alternative_service_.protocol >= NPN_SPDY_MINIMUM_VERSION &&
1258 alternative_service_.protocol <= NPN_SPDY_MAXIMUM_VERSION;
1261 void HttpStreamFactoryImpl::Job::InitSSLConfig(const HostPortPair& server,
1262 SSLConfig* ssl_config,
1263 bool is_proxy) const {
1264 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1265 // When connecting through an HTTPS proxy, disable TLS False Start so
1266 // that client authentication errors can be distinguished between those
1267 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1268 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1269 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1270 // TODO(rch): This assumes that the HTTPS proxy will only request a
1271 // client certificate during the initial handshake.
1272 // http://crbug.com/59292
1273 ssl_config->false_start_enabled = false;
1276 enum {
1277 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1278 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1279 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1280 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1281 FALLBACK_MAX
1284 int fallback = FALLBACK_NONE;
1285 if (ssl_config->version_fallback) {
1286 switch (ssl_config->version_max) {
1287 case SSL_PROTOCOL_VERSION_SSL3:
1288 fallback = FALLBACK_SSL3;
1289 break;
1290 case SSL_PROTOCOL_VERSION_TLS1:
1291 fallback = FALLBACK_TLS1;
1292 break;
1293 case SSL_PROTOCOL_VERSION_TLS1_1:
1294 fallback = FALLBACK_TLS1_1;
1295 break;
1298 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1299 fallback, FALLBACK_MAX);
1301 UMA_HISTOGRAM_BOOLEAN("Net.ConnectionUsedSSLDeprecatedCipherFallback",
1302 ssl_config->enable_deprecated_cipher_suites);
1304 // We also wish to measure the amount of fallback connections for a host that
1305 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1306 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1307 // caused by network middleware rather than buggy HTTPS servers.
1308 const std::string& host = server.host();
1309 if (!is_proxy &&
1310 host.size() >= 10 &&
1311 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1312 (host.size() == 10 || host[host.size()-11] == '.')) {
1313 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1314 fallback, FALLBACK_MAX);
1317 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1318 ssl_config->verify_ev_cert = true;
1320 // Disable Channel ID if privacy mode is enabled.
1321 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1322 ssl_config->channel_id_enabled = false;
1326 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1327 DCHECK(!pac_request_);
1328 DCHECK(session_);
1330 // A failure to resolve the hostname or any error related to establishing a
1331 // TCP connection could be grounds for trying a new proxy configuration.
1333 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1334 // to proxy servers. The hostname in those URLs might fail to resolve if we
1335 // are still using a non-proxy config. We need to check if a proxy config
1336 // now exists that corresponds to a proxy server that could load the URL.
1338 switch (error) {
1339 case ERR_PROXY_CONNECTION_FAILED:
1340 case ERR_NAME_NOT_RESOLVED:
1341 case ERR_INTERNET_DISCONNECTED:
1342 case ERR_ADDRESS_UNREACHABLE:
1343 case ERR_CONNECTION_CLOSED:
1344 case ERR_CONNECTION_TIMED_OUT:
1345 case ERR_CONNECTION_RESET:
1346 case ERR_CONNECTION_REFUSED:
1347 case ERR_CONNECTION_ABORTED:
1348 case ERR_TIMED_OUT:
1349 case ERR_TUNNEL_CONNECTION_FAILED:
1350 case ERR_SOCKS_CONNECTION_FAILED:
1351 // This can happen in the case of trying to talk to a proxy using SSL, and
1352 // ending up talking to a captive portal that supports SSL instead.
1353 case ERR_PROXY_CERTIFICATE_INVALID:
1354 // This can happen when trying to talk SSL to a non-SSL server (Like a
1355 // captive portal).
1356 case ERR_QUIC_PROTOCOL_ERROR:
1357 case ERR_QUIC_HANDSHAKE_FAILED:
1358 case ERR_SSL_PROTOCOL_ERROR:
1359 break;
1360 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1361 // Remap the SOCKS-specific "host unreachable" error to a more
1362 // generic error code (this way consumers like the link doctor
1363 // know to substitute their error page).
1365 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1366 // differentiate between a proxy-side "host not found" versus a proxy-side
1367 // "address unreachable" error, and will report both of these failures as
1368 // ERR_ADDRESS_UNREACHABLE.
1369 return ERR_ADDRESS_UNREACHABLE;
1370 default:
1371 return error;
1374 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1375 return error;
1378 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1379 session_->ssl_client_auth_cache()->Remove(
1380 proxy_info_.proxy_server().host_port_pair());
1383 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1384 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1385 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1386 if (rv == OK || rv == ERR_IO_PENDING) {
1387 // If the error was during connection setup, there is no socket to
1388 // disconnect.
1389 if (connection_->socket())
1390 connection_->socket()->Disconnect();
1391 connection_->Reset();
1392 if (request_)
1393 request_->RemoveRequestFromSpdySessionRequestMap();
1394 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1395 } else {
1396 // If ReconsiderProxyAfterError() failed synchronously, it means
1397 // there was nothing left to fall-back to, so fail the transaction
1398 // with the last connection error we got.
1399 // TODO(eroman): This is a confusing contract, make it more obvious.
1400 rv = error;
1403 return rv;
1406 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1407 DCHECK(using_ssl_);
1408 DCHECK(IsCertificateError(error));
1410 SSLClientSocket* ssl_socket =
1411 static_cast<SSLClientSocket*>(connection_->socket());
1412 ssl_socket->GetSSLInfo(&ssl_info_);
1414 // Add the bad certificate to the set of allowed certificates in the
1415 // SSL config object. This data structure will be consulted after calling
1416 // RestartIgnoringLastError(). And the user will be asked interactively
1417 // before RestartIgnoringLastError() is ever called.
1418 SSLConfig::CertAndStatus bad_cert;
1420 // |ssl_info_.cert| may be NULL if we failed to create
1421 // X509Certificate for whatever reason, but normally it shouldn't
1422 // happen, unless this code is used inside sandbox.
1423 if (ssl_info_.cert.get() == NULL ||
1424 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1425 &bad_cert.der_cert)) {
1426 return error;
1428 bad_cert.cert_status = ssl_info_.cert_status;
1429 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1431 int load_flags = request_info_.load_flags;
1432 if (session_->params().ignore_certificate_errors)
1433 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1434 if (ssl_socket->IgnoreCertError(error, load_flags))
1435 return OK;
1436 return error;
1439 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1440 if (HttpStreamFactory::spdy_enabled())
1441 using_spdy_ = true;
1444 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1445 DCHECK_GE(num_streams_, 0);
1446 return num_streams_ > 0;
1449 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1450 return !IsPreconnecting() && !request_;
1453 void HttpStreamFactoryImpl::Job::ReportJobSucceededForRequest() {
1454 if (using_existing_quic_session_) {
1455 // If an existing session was used, then no TCP connection was
1456 // started.
1457 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE);
1458 } else if (IsAlternate()) {
1459 // This job was the alternate protocol job, and hence won the race.
1460 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE);
1461 } else {
1462 // This job was the normal job, and hence the alternate protocol job lost
1463 // the race.
1464 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE);
1468 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1469 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1470 other_job_status_ = job.job_status_;
1471 other_job_alternative_service_ = job.alternative_service_;
1472 MaybeMarkAlternativeServiceBroken();
1475 void HttpStreamFactoryImpl::Job::MaybeMarkAlternativeServiceBroken() {
1476 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1477 return;
1479 if (IsAlternate()) {
1480 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1481 HistogramBrokenAlternateProtocolLocation(
1482 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1483 session_->http_server_properties()->MarkAlternativeServiceBroken(
1484 alternative_service_);
1486 return;
1489 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1490 HistogramBrokenAlternateProtocolLocation(
1491 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1492 session_->http_server_properties()->MarkAlternativeServiceBroken(
1493 other_job_alternative_service_);
1497 HttpStreamFactoryImpl::Job::ValidSpdySessionPool::ValidSpdySessionPool(
1498 SpdySessionPool* spdy_session_pool,
1499 GURL& origin_url,
1500 bool is_spdy_alternate)
1501 : spdy_session_pool_(spdy_session_pool),
1502 origin_url_(origin_url),
1503 is_spdy_alternate_(is_spdy_alternate) {
1506 int HttpStreamFactoryImpl::Job::ValidSpdySessionPool::FindAvailableSession(
1507 const SpdySessionKey& key,
1508 const BoundNetLog& net_log,
1509 base::WeakPtr<SpdySession>* spdy_session) {
1510 *spdy_session = spdy_session_pool_->FindAvailableSession(key, net_log);
1511 return CheckAlternativeServiceValidityForOrigin(*spdy_session);
1514 int HttpStreamFactoryImpl::Job::ValidSpdySessionPool::
1515 CreateAvailableSessionFromSocket(const SpdySessionKey& key,
1516 scoped_ptr<ClientSocketHandle> connection,
1517 const BoundNetLog& net_log,
1518 int certificate_error_code,
1519 bool is_secure,
1520 base::WeakPtr<SpdySession>* spdy_session) {
1521 *spdy_session = spdy_session_pool_->CreateAvailableSessionFromSocket(
1522 key, connection.Pass(), net_log, certificate_error_code, is_secure);
1523 return CheckAlternativeServiceValidityForOrigin(*spdy_session);
1526 int HttpStreamFactoryImpl::Job::ValidSpdySessionPool::
1527 CheckAlternativeServiceValidityForOrigin(
1528 base::WeakPtr<SpdySession> spdy_session) {
1529 // For a SPDY alternate Job, server_.host() might be different than
1530 // origin_url_.host(), therefore it needs to be verified that the former
1531 // provides a certificate that is valid for the latter.
1532 if (!is_spdy_alternate_ || !spdy_session ||
1533 spdy_session->VerifyDomainAuthentication(origin_url_.host())) {
1534 return OK;
1536 return ERR_ALTERNATIVE_CERT_NOT_VALID_FOR_ORIGIN;
1539 ClientSocketPoolManager::SocketGroupType
1540 HttpStreamFactoryImpl::Job::GetSocketGroup() const {
1541 std::string scheme = origin_url_.scheme();
1542 if (scheme == "https" || scheme == "wss" || IsSpdyAlternate())
1543 return ClientSocketPoolManager::SSL_GROUP;
1545 if (scheme == "ftp")
1546 return ClientSocketPoolManager::FTP_GROUP;
1548 return ClientSocketPoolManager::NORMAL_GROUP;
1551 void HttpStreamFactoryImpl::Job::
1552 MaybeCopyConnectionAttemptsFromClientSocketHandleToRequest() {
1553 if (IsOrphaned() || !connection_)
1554 return;
1556 request_->AddConnectionAttempts(connection_->connection_attempts());
1559 } // namespace net