[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blobe1a547efe9ecbcdfc196b8e6d11e64c240fa4d96
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 AlternativeService alternative_service) {
171 DCHECK(!original_url_.get());
172 original_url_.reset(new GURL(original_url));
173 alternative_service_ = alternative_service;
174 if (alternative_service.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 result = DoLoop(result);
446 if (result == ERR_IO_PENDING)
447 return result;
449 // If there was an error, we should have already resumed the |waiting_job_|,
450 // if there was one.
451 DCHECK(result == OK || waiting_job_ == NULL);
453 if (IsPreconnecting()) {
454 base::MessageLoop::current()->PostTask(
455 FROM_HERE,
456 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
457 ptr_factory_.GetWeakPtr()));
458 return ERR_IO_PENDING;
461 if (IsCertificateError(result)) {
462 // Retrieve SSL information from the socket.
463 GetSSLInfo();
465 next_state_ = STATE_WAITING_USER_ACTION;
466 base::MessageLoop::current()->PostTask(
467 FROM_HERE,
468 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
469 ptr_factory_.GetWeakPtr(), result, ssl_info_));
470 return ERR_IO_PENDING;
473 switch (result) {
474 case ERR_PROXY_AUTH_REQUESTED: {
475 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
476 connection_.get() != NULL);
477 if (!connection_.get())
478 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
479 CHECK(connection_->socket());
480 CHECK(establishing_tunnel_);
482 next_state_ = STATE_WAITING_USER_ACTION;
483 ProxyClientSocket* proxy_socket =
484 static_cast<ProxyClientSocket*>(connection_->socket());
485 base::MessageLoop::current()->PostTask(
486 FROM_HERE,
487 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
488 *proxy_socket->GetConnectResponseInfo(),
489 proxy_socket->GetAuthController()));
490 return ERR_IO_PENDING;
493 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
494 base::MessageLoop::current()->PostTask(
495 FROM_HERE,
496 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
497 connection_->ssl_error_response_info().cert_request_info));
498 return ERR_IO_PENDING;
500 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
501 DCHECK(connection_.get());
502 DCHECK(connection_->socket());
503 DCHECK(establishing_tunnel_);
505 ProxyClientSocket* proxy_socket =
506 static_cast<ProxyClientSocket*>(connection_->socket());
507 base::MessageLoop::current()->PostTask(
508 FROM_HERE,
509 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
510 ptr_factory_.GetWeakPtr(),
511 *proxy_socket->GetConnectResponseInfo(),
512 proxy_socket->CreateConnectResponseStream()));
513 return ERR_IO_PENDING;
516 case OK:
517 job_status_ = STATUS_SUCCEEDED;
518 MaybeMarkAlternateProtocolBroken();
519 next_state_ = STATE_DONE;
520 if (new_spdy_session_.get()) {
521 base::MessageLoop::current()->PostTask(
522 FROM_HERE,
523 base::Bind(&Job::OnNewSpdySessionReadyCallback,
524 ptr_factory_.GetWeakPtr()));
525 } else if (stream_factory_->for_websockets_) {
526 DCHECK(websocket_stream_);
527 base::MessageLoop::current()->PostTask(
528 FROM_HERE,
529 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
530 ptr_factory_.GetWeakPtr()));
531 } else {
532 DCHECK(stream_.get());
533 base::MessageLoop::current()->PostTask(
534 FROM_HERE,
535 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
537 return ERR_IO_PENDING;
539 default:
540 if (job_status_ != STATUS_BROKEN) {
541 DCHECK_EQ(STATUS_RUNNING, job_status_);
542 job_status_ = STATUS_FAILED;
543 MaybeMarkAlternateProtocolBroken();
545 base::MessageLoop::current()->PostTask(
546 FROM_HERE,
547 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
548 result));
549 return ERR_IO_PENDING;
553 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
554 DCHECK_NE(next_state_, STATE_NONE);
555 int rv = result;
556 do {
557 State state = next_state_;
558 next_state_ = STATE_NONE;
559 switch (state) {
560 case STATE_START:
561 DCHECK_EQ(OK, rv);
562 rv = DoStart();
563 break;
564 case STATE_RESOLVE_PROXY:
565 DCHECK_EQ(OK, rv);
566 rv = DoResolveProxy();
567 break;
568 case STATE_RESOLVE_PROXY_COMPLETE:
569 rv = DoResolveProxyComplete(rv);
570 break;
571 case STATE_WAIT_FOR_JOB:
572 DCHECK_EQ(OK, rv);
573 rv = DoWaitForJob();
574 break;
575 case STATE_WAIT_FOR_JOB_COMPLETE:
576 rv = DoWaitForJobComplete(rv);
577 break;
578 case STATE_INIT_CONNECTION:
579 DCHECK_EQ(OK, rv);
580 rv = DoInitConnection();
581 break;
582 case STATE_INIT_CONNECTION_COMPLETE:
583 rv = DoInitConnectionComplete(rv);
584 break;
585 case STATE_WAITING_USER_ACTION:
586 rv = DoWaitingUserAction(rv);
587 break;
588 case STATE_RESTART_TUNNEL_AUTH:
589 DCHECK_EQ(OK, rv);
590 rv = DoRestartTunnelAuth();
591 break;
592 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
593 rv = DoRestartTunnelAuthComplete(rv);
594 break;
595 case STATE_CREATE_STREAM:
596 DCHECK_EQ(OK, rv);
597 rv = DoCreateStream();
598 break;
599 case STATE_CREATE_STREAM_COMPLETE:
600 rv = DoCreateStreamComplete(rv);
601 break;
602 default:
603 NOTREACHED() << "bad state";
604 rv = ERR_FAILED;
605 break;
607 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
608 return rv;
611 int HttpStreamFactoryImpl::Job::StartInternal() {
612 CHECK_EQ(STATE_NONE, next_state_);
613 next_state_ = STATE_START;
614 int rv = RunLoop(OK);
615 DCHECK_EQ(ERR_IO_PENDING, rv);
616 return rv;
619 int HttpStreamFactoryImpl::Job::DoStart() {
620 origin_ = HostPortPair::FromURL(request_info_.url);
621 origin_url_ = stream_factory_->ApplyHostMappingRules(
622 request_info_.url, &origin_);
624 net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB,
625 base::Bind(&NetLogHttpStreamJobCallback,
626 &request_info_.url, &origin_url_,
627 priority_));
629 // Don't connect to restricted ports.
630 bool is_port_allowed = IsPortAllowedByDefault(origin_.port());
631 if (request_info_.url.SchemeIs("ftp")) {
632 // Never share connection with other jobs for FTP requests.
633 DCHECK(!waiting_job_);
635 is_port_allowed = IsPortAllowedByFtp(origin_.port());
637 if (!is_port_allowed && !IsPortAllowedByOverride(origin_.port())) {
638 if (waiting_job_) {
639 waiting_job_->Resume(this);
640 waiting_job_ = NULL;
642 return ERR_UNSAFE_PORT;
645 next_state_ = STATE_RESOLVE_PROXY;
646 return OK;
649 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
650 DCHECK(!pac_request_);
651 DCHECK(session_);
653 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
655 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
656 proxy_info_.UseDirect();
657 return OK;
660 return session_->proxy_service()->ResolveProxy(
661 request_info_.url, request_info_.load_flags, &proxy_info_, io_callback_,
662 &pac_request_, session_->network_delegate(), net_log_);
665 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
666 pac_request_ = NULL;
668 if (result == OK) {
669 // Remove unsupported proxies from the list.
670 int supported_proxies =
671 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP |
672 ProxyServer::SCHEME_HTTPS | ProxyServer::SCHEME_SOCKS4 |
673 ProxyServer::SCHEME_SOCKS5;
675 if (session_->params().enable_quic_for_proxies)
676 supported_proxies |= ProxyServer::SCHEME_QUIC;
678 proxy_info_.RemoveProxiesWithoutScheme(supported_proxies);
680 if (proxy_info_.is_empty()) {
681 // No proxies/direct to choose from. This happens when we don't support
682 // any of the proxies in the returned list.
683 result = ERR_NO_SUPPORTED_PROXIES;
684 } else if (using_quic_ &&
685 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
686 // QUIC can not be spoken to non-QUIC proxies. This error should not be
687 // user visible, because the non-alternate job should be resumed.
688 result = ERR_NO_SUPPORTED_PROXIES;
692 if (result != OK) {
693 if (waiting_job_) {
694 waiting_job_->Resume(this);
695 waiting_job_ = NULL;
697 return result;
700 if (blocking_job_)
701 next_state_ = STATE_WAIT_FOR_JOB;
702 else
703 next_state_ = STATE_INIT_CONNECTION;
704 return OK;
707 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
708 bool rv = session_->params().force_spdy_always &&
709 session_->params().force_spdy_over_ssl;
710 return rv && !session_->HasSpdyExclusion(origin_);
713 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
714 bool rv = session_->params().force_spdy_always &&
715 !session_->params().force_spdy_over_ssl;
716 return rv && !session_->HasSpdyExclusion(origin_);
719 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
720 return session_->params().enable_quic &&
721 session_->params().origin_to_force_quic_on.Equals(origin_) &&
722 proxy_info_.is_direct();
725 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
726 DCHECK(blocking_job_);
727 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
728 return ERR_IO_PENDING;
731 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
732 DCHECK(!blocking_job_);
733 DCHECK_EQ(OK, result);
734 next_state_ = STATE_INIT_CONNECTION;
735 return OK;
738 int HttpStreamFactoryImpl::Job::DoInitConnection() {
739 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462812 is fixed.
740 tracked_objects::ScopedTracker tracking_profile(
741 FROM_HERE_WITH_EXPLICIT_FUNCTION(
742 "462812 HttpStreamFactoryImpl::Job::DoInitConnection"));
743 DCHECK(!blocking_job_);
744 DCHECK(!connection_->is_initialized());
745 DCHECK(proxy_info_.proxy_server().is_valid());
746 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
748 using_ssl_ = request_info_.url.SchemeIs("https") ||
749 request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
750 using_spdy_ = false;
752 if (ShouldForceQuic())
753 using_quic_ = true;
755 DCHECK(!using_quic_ || session_->params().enable_quic);
757 if (proxy_info_.is_quic()) {
758 using_quic_ = true;
759 DCHECK(session_->params().enable_quic_for_proxies);
762 if (using_quic_) {
763 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
764 NOTREACHED();
765 // TODO(rch): support QUIC proxies for HTTPS urls.
766 return ERR_NOT_IMPLEMENTED;
768 HostPortPair destination = proxy_info_.is_quic() ?
769 proxy_info_.proxy_server().host_port_pair() : origin_;
770 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
771 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
772 int rv = quic_request_.Request(
773 destination, secure_quic, request_info_.privacy_mode,
774 request_info_.method, net_log_, io_callback_);
775 if (rv == OK) {
776 using_existing_quic_session_ = true;
777 } else {
778 // OK, there's no available QUIC session. Let |waiting_job_| resume
779 // if it's paused.
780 if (waiting_job_) {
781 waiting_job_->Resume(this);
782 waiting_job_ = NULL;
785 return rv;
788 // Check first if we have a spdy session for this group. If so, then go
789 // straight to using that.
790 SpdySessionKey spdy_session_key = GetSpdySessionKey();
791 base::WeakPtr<SpdySession> spdy_session =
792 session_->spdy_session_pool()->FindAvailableSession(
793 spdy_session_key, net_log_);
794 if (spdy_session && CanUseExistingSpdySession()) {
795 // If we're preconnecting, but we already have a SpdySession, we don't
796 // actually need to preconnect any sockets, so we're done.
797 if (IsPreconnecting())
798 return OK;
799 using_spdy_ = true;
800 next_state_ = STATE_CREATE_STREAM;
801 existing_spdy_session_ = spdy_session;
802 return OK;
803 } else if (request_ && !request_->HasSpdySessionKey() &&
804 (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
805 // Update the spdy session key for the request that launched this job.
806 request_->SetSpdySessionKey(spdy_session_key);
809 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
810 // paused.
812 if (waiting_job_) {
813 waiting_job_->Resume(this);
814 waiting_job_ = NULL;
817 if (proxy_info_.is_http() || proxy_info_.is_https())
818 establishing_tunnel_ = using_ssl_;
820 bool want_spdy_over_npn = original_url_ != NULL;
822 if (proxy_info_.is_https()) {
823 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
824 &proxy_ssl_config_,
825 true /* is a proxy server */);
826 // Disable revocation checking for HTTPS proxies since the revocation
827 // requests are probably going to need to go through the proxy too.
828 proxy_ssl_config_.rev_checking_enabled = false;
830 if (using_ssl_) {
831 InitSSLConfig(origin_, &server_ssl_config_,
832 false /* not a proxy server */);
835 base::WeakPtr<HttpServerProperties> http_server_properties =
836 session_->http_server_properties();
837 if (http_server_properties) {
838 http_server_properties->MaybeForceHTTP11(origin_, &server_ssl_config_);
839 if (proxy_info_.is_http() || proxy_info_.is_https()) {
840 http_server_properties->MaybeForceHTTP11(
841 proxy_info_.proxy_server().host_port_pair(), &proxy_ssl_config_);
845 if (IsPreconnecting()) {
846 DCHECK(!stream_factory_->for_websockets_);
847 return PreconnectSocketsForHttpRequest(
848 origin_url_,
849 request_info_.extra_headers,
850 request_info_.load_flags,
851 priority_,
852 session_,
853 proxy_info_,
854 ShouldForceSpdySSL(),
855 want_spdy_over_npn,
856 server_ssl_config_,
857 proxy_ssl_config_,
858 request_info_.privacy_mode,
859 net_log_,
860 num_streams_);
863 // If we can't use a SPDY session, don't both checking for one after
864 // the hostname is resolved.
865 OnHostResolutionCallback resolution_callback = CanUseExistingSpdySession() ?
866 base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
867 GetSpdySessionKey()) :
868 OnHostResolutionCallback();
869 if (stream_factory_->for_websockets_) {
870 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
871 SSLConfig websocket_server_ssl_config = server_ssl_config_;
872 websocket_server_ssl_config.next_protos.clear();
873 return InitSocketHandleForWebSocketRequest(
874 origin_url_, request_info_.extra_headers, request_info_.load_flags,
875 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
876 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
877 request_info_.privacy_mode, net_log_,
878 connection_.get(), resolution_callback, io_callback_);
881 return InitSocketHandleForHttpRequest(
882 origin_url_, request_info_.extra_headers, request_info_.load_flags,
883 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
884 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
885 request_info_.privacy_mode, net_log_,
886 connection_.get(), resolution_callback, io_callback_);
889 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
890 if (IsPreconnecting()) {
891 if (using_quic_)
892 return result;
893 DCHECK_EQ(OK, result);
894 return OK;
897 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
898 // We found a SPDY connection after resolving the host. This is
899 // probably an IP pooled connection.
900 SpdySessionKey spdy_session_key = GetSpdySessionKey();
901 existing_spdy_session_ =
902 session_->spdy_session_pool()->FindAvailableSession(
903 spdy_session_key, net_log_);
904 if (existing_spdy_session_) {
905 using_spdy_ = true;
906 next_state_ = STATE_CREATE_STREAM;
907 } else {
908 // It is possible that the spdy session no longer exists.
909 ReturnToStateInitConnection(true /* close connection */);
911 return OK;
914 if (proxy_info_.is_quic() && using_quic_ &&
915 (result == ERR_QUIC_PROTOCOL_ERROR ||
916 result == ERR_QUIC_HANDSHAKE_FAILED)) {
917 using_quic_ = false;
918 return ReconsiderProxyAfterError(result);
921 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
922 // errors, such as ignoring certificate errors for Alternate-Protocol.
923 if (result < 0 && waiting_job_) {
924 waiting_job_->Resume(this);
925 waiting_job_ = NULL;
928 // |result| may be the result of any of the stacked pools. The following
929 // logic is used when determining how to interpret an error.
930 // If |result| < 0:
931 // and connection_->socket() != NULL, then the SSL handshake ran and it
932 // is a potentially recoverable error.
933 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
934 // then the SSL handshake ran with an unrecoverable error.
935 // otherwise, the error came from one of the other pools.
936 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
937 connection_->is_ssl_error());
939 if (ssl_started && (result == OK || IsCertificateError(result))) {
940 if (using_quic_ && result == OK) {
941 was_npn_negotiated_ = true;
942 NextProto protocol_negotiated =
943 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
944 protocol_negotiated_ = protocol_negotiated;
945 } else {
946 SSLClientSocket* ssl_socket =
947 static_cast<SSLClientSocket*>(connection_->socket());
948 if (ssl_socket->WasNpnNegotiated()) {
949 was_npn_negotiated_ = true;
950 std::string proto;
951 SSLClientSocket::NextProtoStatus status =
952 ssl_socket->GetNextProto(&proto);
953 NextProto protocol_negotiated =
954 SSLClientSocket::NextProtoFromString(proto);
955 protocol_negotiated_ = protocol_negotiated;
956 net_log_.AddEvent(
957 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
958 base::Bind(&NetLogHttpStreamProtoCallback,
959 status, &proto));
960 if (ssl_socket->was_spdy_negotiated())
961 SwitchToSpdyMode();
963 if (ShouldForceSpdySSL())
964 SwitchToSpdyMode();
966 } else if (proxy_info_.is_https() && connection_->socket() &&
967 result == OK) {
968 ProxyClientSocket* proxy_socket =
969 static_cast<ProxyClientSocket*>(connection_->socket());
970 if (proxy_socket->IsUsingSpdy()) {
971 was_npn_negotiated_ = true;
972 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
973 SwitchToSpdyMode();
977 // We may be using spdy without SSL
978 if (ShouldForceSpdyWithoutSSL())
979 SwitchToSpdyMode();
981 if (result == ERR_PROXY_AUTH_REQUESTED ||
982 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
983 DCHECK(!ssl_started);
984 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
985 // SSL socket, but there was an error before that could happen. This
986 // puts the in progress HttpProxy socket into |connection_| in order to
987 // complete the auth (or read the response body). The tunnel restart code
988 // is careful to remove it before returning control to the rest of this
989 // class.
990 connection_.reset(connection_->release_pending_http_proxy_connection());
991 return result;
994 if (!ssl_started && result < 0 && original_url_.get()) {
995 job_status_ = STATUS_BROKEN;
996 MaybeMarkAlternateProtocolBroken();
997 return result;
1000 if (using_quic_) {
1001 if (result < 0) {
1002 job_status_ = STATUS_BROKEN;
1003 MaybeMarkAlternateProtocolBroken();
1004 return result;
1006 stream_ = quic_request_.ReleaseStream();
1007 next_state_ = STATE_NONE;
1008 return OK;
1011 if (result < 0 && !ssl_started)
1012 return ReconsiderProxyAfterError(result);
1013 establishing_tunnel_ = false;
1015 if (connection_->socket()) {
1016 // We officially have a new connection. Record the type.
1017 if (!connection_->is_reused()) {
1018 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
1019 UpdateConnectionTypeHistograms(type);
1023 // Handle SSL errors below.
1024 if (using_ssl_) {
1025 DCHECK(ssl_started);
1026 if (IsCertificateError(result)) {
1027 if (using_spdy_ && original_url_.get() &&
1028 original_url_->SchemeIs("http")) {
1029 // We ignore certificate errors for http over spdy.
1030 spdy_certificate_error_ = result;
1031 result = OK;
1032 } else {
1033 result = HandleCertificateError(result);
1034 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1035 ReturnToStateInitConnection(true /* close connection */);
1036 return result;
1040 if (result < 0)
1041 return result;
1044 next_state_ = STATE_CREATE_STREAM;
1045 return OK;
1048 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1049 // This state indicates that the stream request is in a partially
1050 // completed state, and we've called back to the delegate for more
1051 // information.
1053 // We're always waiting here for the delegate to call us back.
1054 return ERR_IO_PENDING;
1057 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1058 base::WeakPtr<SpdySession> session, bool direct) {
1059 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1060 // implemented.
1061 if (stream_factory_->for_websockets_)
1062 return ERR_NOT_IMPLEMENTED;
1064 // TODO(willchan): Delete this code, because eventually, the
1065 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1066 // will know when SpdySessions become available.
1068 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1069 stream_.reset(new SpdyHttpStream(session, use_relative_url));
1070 return OK;
1073 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1074 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462811 is fixed.
1075 tracked_objects::ScopedTracker tracking_profile(
1076 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1077 "462811 HttpStreamFactoryImpl::Job::DoCreateStream"));
1078 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1080 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1082 // We only set the socket motivation if we're the first to use
1083 // this socket. Is there a race for two SPDY requests? We really
1084 // need to plumb this through to the connect level.
1085 if (connection_->socket() && !connection_->is_reused())
1086 SetSocketMotivation();
1088 if (!using_spdy_) {
1089 // We may get ftp scheme when fetching ftp resources through proxy.
1090 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1091 (request_info_.url.SchemeIs("http") ||
1092 request_info_.url.SchemeIs("ftp"));
1093 if (stream_factory_->for_websockets_) {
1094 DCHECK(request_);
1095 DCHECK(request_->websocket_handshake_stream_create_helper());
1096 websocket_stream_.reset(
1097 request_->websocket_handshake_stream_create_helper()
1098 ->CreateBasicStream(connection_.Pass(), using_proxy));
1099 } else {
1100 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1102 return OK;
1105 CHECK(!stream_.get());
1107 bool direct = true;
1108 const ProxyServer& proxy_server = proxy_info_.proxy_server();
1109 PrivacyMode privacy_mode = request_info_.privacy_mode;
1110 if (IsHttpsProxyAndHttpUrl())
1111 direct = false;
1113 if (existing_spdy_session_.get()) {
1114 // We picked up an existing session, so we don't need our socket.
1115 if (connection_->socket())
1116 connection_->socket()->Disconnect();
1117 connection_->Reset();
1119 int set_result = SetSpdyHttpStream(existing_spdy_session_, direct);
1120 existing_spdy_session_.reset();
1121 return set_result;
1124 SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1125 if (IsHttpsProxyAndHttpUrl()) {
1126 // If we don't have a direct SPDY session, and we're using an HTTPS
1127 // proxy, then we might have a SPDY session to the proxy.
1128 // We never use privacy mode for connection to proxy server.
1129 spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1130 ProxyServer::Direct(),
1131 PRIVACY_MODE_DISABLED);
1134 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1135 base::WeakPtr<SpdySession> spdy_session =
1136 spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1138 if (spdy_session) {
1139 return SetSpdyHttpStream(spdy_session, direct);
1142 spdy_session =
1143 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1144 connection_.Pass(),
1145 net_log_,
1146 spdy_certificate_error_,
1147 using_ssl_);
1148 if (!spdy_session->HasAcceptableTransportSecurity()) {
1149 spdy_session->CloseSessionOnError(
1150 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1151 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1154 new_spdy_session_ = spdy_session;
1155 spdy_session_direct_ = direct;
1156 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1157 base::WeakPtr<HttpServerProperties> http_server_properties =
1158 session_->http_server_properties();
1159 if (http_server_properties)
1160 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1162 // Create a SpdyHttpStream attached to the session;
1163 // OnNewSpdySessionReadyCallback is not called until an event loop
1164 // iteration later, so if the SpdySession is closed between then, allow
1165 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1166 // bubble up to the request.
1167 return SetSpdyHttpStream(new_spdy_session_, spdy_session_direct_);
1170 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1171 if (result < 0)
1172 return result;
1174 session_->proxy_service()->ReportSuccess(proxy_info_,
1175 session_->network_delegate());
1176 next_state_ = STATE_NONE;
1177 return OK;
1180 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1181 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1182 ProxyClientSocket* proxy_socket =
1183 static_cast<ProxyClientSocket*>(connection_->socket());
1184 return proxy_socket->RestartWithAuth(io_callback_);
1187 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1188 if (result == ERR_PROXY_AUTH_REQUESTED)
1189 return result;
1191 if (result == OK) {
1192 // Now that we've got the HttpProxyClientSocket connected. We have
1193 // to release it as an idle socket into the pool and start the connection
1194 // process from the beginning. Trying to pass it in with the
1195 // SSLSocketParams might cause a deadlock since params are dispatched
1196 // interchangeably. This request won't necessarily get this http proxy
1197 // socket, but there will be forward progress.
1198 establishing_tunnel_ = false;
1199 ReturnToStateInitConnection(false /* do not close connection */);
1200 return OK;
1203 return ReconsiderProxyAfterError(result);
1206 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1207 bool close_connection) {
1208 if (close_connection && connection_->socket())
1209 connection_->socket()->Disconnect();
1210 connection_->Reset();
1212 if (request_)
1213 request_->RemoveRequestFromSpdySessionRequestMap();
1215 next_state_ = STATE_INIT_CONNECTION;
1218 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1219 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1220 connection_->socket()->SetSubresourceSpeculation();
1221 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1222 connection_->socket()->SetOmniboxSpeculation();
1223 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1226 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1227 if (!proxy_info_.is_https())
1228 return false;
1229 if (original_url_.get()) {
1230 // We currently only support Alternate-Protocol where the original scheme
1231 // is http.
1232 DCHECK(original_url_->SchemeIs("http"));
1233 return original_url_->SchemeIs("http");
1235 return request_info_.url.SchemeIs("http");
1238 // Sets several fields of ssl_config for the given origin_server based on the
1239 // proxy info and other factors.
1240 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1241 const HostPortPair& origin_server,
1242 SSLConfig* ssl_config,
1243 bool is_proxy) const {
1244 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1245 // When connecting through an HTTPS proxy, disable TLS False Start so
1246 // that client authentication errors can be distinguished between those
1247 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1248 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1249 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1250 // TODO(rch): This assumes that the HTTPS proxy will only request a
1251 // client certificate during the initial handshake.
1252 // http://crbug.com/59292
1253 ssl_config->false_start_enabled = false;
1256 enum {
1257 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1258 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1259 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1260 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1261 FALLBACK_MAX
1264 int fallback = FALLBACK_NONE;
1265 if (ssl_config->version_fallback) {
1266 switch (ssl_config->version_max) {
1267 case SSL_PROTOCOL_VERSION_SSL3:
1268 fallback = FALLBACK_SSL3;
1269 break;
1270 case SSL_PROTOCOL_VERSION_TLS1:
1271 fallback = FALLBACK_TLS1;
1272 break;
1273 case SSL_PROTOCOL_VERSION_TLS1_1:
1274 fallback = FALLBACK_TLS1_1;
1275 break;
1278 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1279 fallback, FALLBACK_MAX);
1281 // We also wish to measure the amount of fallback connections for a host that
1282 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1283 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1284 // caused by network middleware rather than buggy HTTPS servers.
1285 const std::string& host = origin_server.host();
1286 if (!is_proxy &&
1287 host.size() >= 10 &&
1288 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1289 (host.size() == 10 || host[host.size()-11] == '.')) {
1290 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1291 fallback, FALLBACK_MAX);
1294 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1295 ssl_config->verify_ev_cert = true;
1297 // Disable Channel ID if privacy mode is enabled.
1298 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1299 ssl_config->channel_id_enabled = false;
1303 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1304 DCHECK(!pac_request_);
1305 DCHECK(session_);
1307 // A failure to resolve the hostname or any error related to establishing a
1308 // TCP connection could be grounds for trying a new proxy configuration.
1310 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1311 // to proxy servers. The hostname in those URLs might fail to resolve if we
1312 // are still using a non-proxy config. We need to check if a proxy config
1313 // now exists that corresponds to a proxy server that could load the URL.
1315 switch (error) {
1316 case ERR_PROXY_CONNECTION_FAILED:
1317 case ERR_NAME_NOT_RESOLVED:
1318 case ERR_INTERNET_DISCONNECTED:
1319 case ERR_ADDRESS_UNREACHABLE:
1320 case ERR_CONNECTION_CLOSED:
1321 case ERR_CONNECTION_TIMED_OUT:
1322 case ERR_CONNECTION_RESET:
1323 case ERR_CONNECTION_REFUSED:
1324 case ERR_CONNECTION_ABORTED:
1325 case ERR_TIMED_OUT:
1326 case ERR_TUNNEL_CONNECTION_FAILED:
1327 case ERR_SOCKS_CONNECTION_FAILED:
1328 // This can happen in the case of trying to talk to a proxy using SSL, and
1329 // ending up talking to a captive portal that supports SSL instead.
1330 case ERR_PROXY_CERTIFICATE_INVALID:
1331 // This can happen when trying to talk SSL to a non-SSL server (Like a
1332 // captive portal).
1333 case ERR_QUIC_PROTOCOL_ERROR:
1334 case ERR_QUIC_HANDSHAKE_FAILED:
1335 case ERR_SSL_PROTOCOL_ERROR:
1336 break;
1337 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1338 // Remap the SOCKS-specific "host unreachable" error to a more
1339 // generic error code (this way consumers like the link doctor
1340 // know to substitute their error page).
1342 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1343 // differentiate between a proxy-side "host not found" versus a proxy-side
1344 // "address unreachable" error, and will report both of these failures as
1345 // ERR_ADDRESS_UNREACHABLE.
1346 return ERR_ADDRESS_UNREACHABLE;
1347 default:
1348 return error;
1351 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1352 return error;
1355 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1356 session_->ssl_client_auth_cache()->Remove(
1357 proxy_info_.proxy_server().host_port_pair());
1360 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1361 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1362 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1363 if (rv == OK || rv == ERR_IO_PENDING) {
1364 // If the error was during connection setup, there is no socket to
1365 // disconnect.
1366 if (connection_->socket())
1367 connection_->socket()->Disconnect();
1368 connection_->Reset();
1369 if (request_)
1370 request_->RemoveRequestFromSpdySessionRequestMap();
1371 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1372 } else {
1373 // If ReconsiderProxyAfterError() failed synchronously, it means
1374 // there was nothing left to fall-back to, so fail the transaction
1375 // with the last connection error we got.
1376 // TODO(eroman): This is a confusing contract, make it more obvious.
1377 rv = error;
1380 return rv;
1383 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1384 DCHECK(using_ssl_);
1385 DCHECK(IsCertificateError(error));
1387 SSLClientSocket* ssl_socket =
1388 static_cast<SSLClientSocket*>(connection_->socket());
1389 ssl_socket->GetSSLInfo(&ssl_info_);
1391 // Add the bad certificate to the set of allowed certificates in the
1392 // SSL config object. This data structure will be consulted after calling
1393 // RestartIgnoringLastError(). And the user will be asked interactively
1394 // before RestartIgnoringLastError() is ever called.
1395 SSLConfig::CertAndStatus bad_cert;
1397 // |ssl_info_.cert| may be NULL if we failed to create
1398 // X509Certificate for whatever reason, but normally it shouldn't
1399 // happen, unless this code is used inside sandbox.
1400 if (ssl_info_.cert.get() == NULL ||
1401 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1402 &bad_cert.der_cert)) {
1403 return error;
1405 bad_cert.cert_status = ssl_info_.cert_status;
1406 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1408 int load_flags = request_info_.load_flags;
1409 if (session_->params().ignore_certificate_errors)
1410 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1411 if (ssl_socket->IgnoreCertError(error, load_flags))
1412 return OK;
1413 return error;
1416 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1417 if (HttpStreamFactory::spdy_enabled())
1418 using_spdy_ = true;
1421 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1422 DCHECK_GE(num_streams_, 0);
1423 return num_streams_ > 0;
1426 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1427 return !IsPreconnecting() && !request_;
1430 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1431 if (using_existing_quic_session_) {
1432 // If an existing session was used, then no TCP connection was
1433 // started.
1434 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE);
1435 } else if (original_url_) {
1436 // This job was the alternate protocol job, and hence won the race.
1437 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE);
1438 } else {
1439 // This job was the normal job, and hence the alternate protocol job lost
1440 // the race.
1441 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE);
1445 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1446 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1447 other_job_status_ = job.job_status_;
1448 other_job_alternative_service_ = job.alternative_service_;
1449 MaybeMarkAlternateProtocolBroken();
1452 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1453 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1454 return;
1456 bool is_alternate_protocol_job = original_url_.get() != NULL;
1457 if (is_alternate_protocol_job) {
1458 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1459 HistogramBrokenAlternateProtocolLocation(
1460 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1461 session_->http_server_properties()->MarkAlternativeServiceBroken(
1462 alternative_service_);
1464 return;
1467 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1468 HistogramBrokenAlternateProtocolLocation(
1469 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1470 session_->http_server_properties()->MarkAlternativeServiceBroken(
1471 other_job_alternative_service_);
1475 } // namespace net