Put screenshot.py back to work
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blob83694437450b028590ae8617ad8ce1ec05071154
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/http/http_stream_factory_impl_job.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/values.h"
17 #include "build/build_config.h"
18 #include "net/base/connection_type_histograms.h"
19 #include "net/base/net_log.h"
20 #include "net/base/net_util.h"
21 #include "net/http/http_basic_stream.h"
22 #include "net/http/http_network_session.h"
23 #include "net/http/http_proxy_client_socket.h"
24 #include "net/http/http_proxy_client_socket_pool.h"
25 #include "net/http/http_request_info.h"
26 #include "net/http/http_server_properties.h"
27 #include "net/http/http_stream_factory.h"
28 #include "net/http/http_stream_factory_impl_request.h"
29 #include "net/quic/quic_http_stream.h"
30 #include "net/socket/client_socket_handle.h"
31 #include "net/socket/client_socket_pool.h"
32 #include "net/socket/client_socket_pool_manager.h"
33 #include "net/socket/socks_client_socket_pool.h"
34 #include "net/socket/ssl_client_socket.h"
35 #include "net/socket/ssl_client_socket_pool.h"
36 #include "net/spdy/spdy_http_stream.h"
37 #include "net/spdy/spdy_session.h"
38 #include "net/spdy/spdy_session_pool.h"
39 #include "net/ssl/ssl_cert_request_info.h"
41 namespace net {
43 // Returns parameters associated with the start of a HTTP stream job.
44 base::Value* NetLogHttpStreamJobCallback(const GURL* original_url,
45 const GURL* url,
46 RequestPriority priority,
47 NetLog::LogLevel /* log_level */) {
48 base::DictionaryValue* dict = new base::DictionaryValue();
49 dict->SetString("original_url", original_url->GetOrigin().spec());
50 dict->SetString("url", url->GetOrigin().spec());
51 dict->SetString("priority", RequestPriorityToString(priority));
52 return dict;
55 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
56 // stream.
57 base::Value* NetLogHttpStreamProtoCallback(
58 const SSLClientSocket::NextProtoStatus status,
59 const std::string* proto,
60 NetLog::LogLevel /* log_level */) {
61 base::DictionaryValue* dict = new base::DictionaryValue();
63 dict->SetString("next_proto_status",
64 SSLClientSocket::NextProtoStatusToString(status));
65 dict->SetString("proto", *proto);
66 return dict;
69 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
70 HttpNetworkSession* session,
71 const HttpRequestInfo& request_info,
72 RequestPriority priority,
73 const SSLConfig& server_ssl_config,
74 const SSLConfig& proxy_ssl_config,
75 NetLog* net_log)
76 : request_(NULL),
77 request_info_(request_info),
78 priority_(priority),
79 server_ssl_config_(server_ssl_config),
80 proxy_ssl_config_(proxy_ssl_config),
81 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
82 io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
83 connection_(new ClientSocketHandle),
84 session_(session),
85 stream_factory_(stream_factory),
86 next_state_(STATE_NONE),
87 pac_request_(NULL),
88 blocking_job_(NULL),
89 waiting_job_(NULL),
90 using_ssl_(false),
91 using_spdy_(false),
92 using_quic_(false),
93 quic_request_(session_->quic_stream_factory()),
94 using_existing_quic_session_(false),
95 spdy_certificate_error_(OK),
96 establishing_tunnel_(false),
97 was_npn_negotiated_(false),
98 protocol_negotiated_(kProtoUnknown),
99 num_streams_(0),
100 spdy_session_direct_(false),
101 job_status_(STATUS_RUNNING),
102 other_job_status_(STATUS_RUNNING),
103 ptr_factory_(this) {
104 DCHECK(stream_factory);
105 DCHECK(session);
108 HttpStreamFactoryImpl::Job::~Job() {
109 net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
111 // When we're in a partially constructed state, waiting for the user to
112 // provide certificate handling information or authentication, we can't reuse
113 // this stream at all.
114 if (next_state_ == STATE_WAITING_USER_ACTION) {
115 connection_->socket()->Disconnect();
116 connection_.reset();
119 if (pac_request_)
120 session_->proxy_service()->CancelPacRequest(pac_request_);
122 // The stream could be in a partial state. It is not reusable.
123 if (stream_.get() && next_state_ != STATE_DONE)
124 stream_->Close(true /* not reusable */);
127 void HttpStreamFactoryImpl::Job::Start(Request* request) {
128 DCHECK(request);
129 request_ = request;
130 StartInternal();
133 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
134 DCHECK_GT(num_streams, 0);
135 base::WeakPtr<HttpServerProperties> http_server_properties =
136 session_->http_server_properties();
137 if (http_server_properties && http_server_properties->SupportsSpdy(
138 HostPortPair::FromURL(request_info_.url))) {
139 num_streams_ = 1;
140 } else {
141 num_streams_ = num_streams;
143 return StartInternal();
146 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
147 const AuthCredentials& credentials) {
148 DCHECK(establishing_tunnel_);
149 next_state_ = STATE_RESTART_TUNNEL_AUTH;
150 stream_.reset();
151 return RunLoop(OK);
154 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
155 switch (next_state_) {
156 case STATE_RESOLVE_PROXY_COMPLETE:
157 return session_->proxy_service()->GetLoadState(pac_request_);
158 case STATE_INIT_CONNECTION_COMPLETE:
159 case STATE_CREATE_STREAM_COMPLETE:
160 return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
161 default:
162 return LOAD_STATE_IDLE;
166 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
167 const GURL& original_url,
168 AlternateProtocolInfo alternate) {
169 DCHECK(!original_url_.get());
170 original_url_.reset(new GURL(original_url));
171 if (alternate.protocol == QUIC) {
172 DCHECK(session_->params().enable_quic);
173 using_quic_ = true;
177 void HttpStreamFactoryImpl::Job::WaitFor(Job* job) {
178 DCHECK_EQ(STATE_NONE, next_state_);
179 DCHECK_EQ(STATE_NONE, job->next_state_);
180 DCHECK(!blocking_job_);
181 DCHECK(!job->waiting_job_);
182 blocking_job_ = job;
183 job->waiting_job_ = this;
186 void HttpStreamFactoryImpl::Job::Resume(Job* job) {
187 DCHECK_EQ(blocking_job_, job);
188 blocking_job_ = NULL;
190 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
191 // Unblock |this|.
192 if (next_state_ == STATE_WAIT_FOR_JOB_COMPLETE) {
193 base::MessageLoop::current()->PostTask(
194 FROM_HERE,
195 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete,
196 ptr_factory_.GetWeakPtr(), OK));
200 void HttpStreamFactoryImpl::Job::Orphan(const Request* request) {
201 DCHECK_EQ(request_, request);
202 request_ = NULL;
203 if (blocking_job_) {
204 // We've been orphaned, but there's a job we're blocked on. Don't bother
205 // racing, just cancel ourself.
206 DCHECK(blocking_job_->waiting_job_);
207 blocking_job_->waiting_job_ = NULL;
208 blocking_job_ = NULL;
209 if (stream_factory_->for_websockets_ &&
210 connection_ && connection_->socket()) {
211 connection_->socket()->Disconnect();
213 stream_factory_->OnOrphanedJobComplete(this);
214 } else if (stream_factory_->for_websockets_) {
215 // We cancel this job because a WebSocketHandshakeStream can't be created
216 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
217 // the Request class and isn't accessible from this job.
218 if (connection_ && connection_->socket()) {
219 connection_->socket()->Disconnect();
221 stream_factory_->OnOrphanedJobComplete(this);
225 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) {
226 priority_ = priority;
227 // TODO(akalin): Propagate this to |connection_| and maybe the
228 // preconnect state.
231 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
232 return was_npn_negotiated_;
235 NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const {
236 return protocol_negotiated_;
239 bool HttpStreamFactoryImpl::Job::using_spdy() const {
240 return using_spdy_;
243 const SSLConfig& HttpStreamFactoryImpl::Job::server_ssl_config() const {
244 return server_ssl_config_;
247 const SSLConfig& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
248 return proxy_ssl_config_;
251 const ProxyInfo& HttpStreamFactoryImpl::Job::proxy_info() const {
252 return proxy_info_;
255 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
256 DCHECK(using_ssl_);
257 DCHECK(!establishing_tunnel_);
258 DCHECK(connection_.get() && connection_->socket());
259 SSLClientSocket* ssl_socket =
260 static_cast<SSLClientSocket*>(connection_->socket());
261 ssl_socket->GetSSLInfo(&ssl_info_);
264 SpdySessionKey HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
265 // In the case that we're using an HTTPS proxy for an HTTP url,
266 // we look for a SPDY session *to* the proxy, instead of to the
267 // origin server.
268 PrivacyMode privacy_mode = request_info_.privacy_mode;
269 if (IsHttpsProxyAndHttpUrl()) {
270 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
271 ProxyServer::Direct(),
272 privacy_mode);
273 } else {
274 return SpdySessionKey(origin_,
275 proxy_info_.proxy_server(),
276 privacy_mode);
280 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
281 // We need to make sure that if a spdy session was created for
282 // https://somehost/ that we don't use that session for http://somehost:443/.
283 // The only time we can use an existing session is if the request URL is
284 // https (the normal case) or if we're connection to a SPDY proxy, or
285 // if we're running with force_spdy_always_. crbug.com/133176
286 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
287 // working.
288 return request_info_.url.SchemeIs("https") ||
289 proxy_info_.proxy_server().is_https() ||
290 session_->params().force_spdy_always;
293 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
294 DCHECK(stream_.get());
295 DCHECK(!IsPreconnecting());
296 DCHECK(!stream_factory_->for_websockets_);
297 if (IsOrphaned()) {
298 stream_factory_->OnOrphanedJobComplete(this);
299 } else {
300 request_->Complete(was_npn_negotiated(),
301 protocol_negotiated(),
302 using_spdy(),
303 net_log_);
304 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
305 stream_.release());
307 // |this| may be deleted after this call.
310 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
311 DCHECK(websocket_stream_);
312 DCHECK(!IsPreconnecting());
313 DCHECK(stream_factory_->for_websockets_);
314 // An orphaned WebSocket job will be closed immediately and
315 // never be ready.
316 DCHECK(!IsOrphaned());
317 request_->Complete(was_npn_negotiated(),
318 protocol_negotiated(),
319 using_spdy(),
320 net_log_);
321 request_->OnWebSocketHandshakeStreamReady(this,
322 server_ssl_config_,
323 proxy_info_,
324 websocket_stream_.release());
325 // |this| may be deleted after this call.
328 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
329 DCHECK(stream_.get());
330 DCHECK(!IsPreconnecting());
331 DCHECK(using_spdy());
332 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
333 // NULL at this point if the SpdySession closed immediately after creation.
334 base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
335 new_spdy_session_.reset();
337 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
338 // rather than notifying |request_| directly.
339 if (IsOrphaned()) {
340 if (spdy_session) {
341 stream_factory_->OnNewSpdySessionReady(
342 spdy_session, spdy_session_direct_, server_ssl_config_, proxy_info_,
343 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_);
345 stream_factory_->OnOrphanedJobComplete(this);
346 } else {
347 request_->OnNewSpdySessionReady(
348 this, stream_.Pass(), spdy_session, spdy_session_direct_);
350 // |this| may be deleted after this call.
353 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result) {
354 DCHECK(!IsPreconnecting());
355 if (IsOrphaned())
356 stream_factory_->OnOrphanedJobComplete(this);
357 else
358 request_->OnStreamFailed(this, result, server_ssl_config_);
359 // |this| may be deleted after this call.
362 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
363 int result, const SSLInfo& ssl_info) {
364 DCHECK(!IsPreconnecting());
365 if (IsOrphaned())
366 stream_factory_->OnOrphanedJobComplete(this);
367 else
368 request_->OnCertificateError(this, result, server_ssl_config_, ssl_info);
369 // |this| may be deleted after this call.
372 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
373 const HttpResponseInfo& response,
374 HttpAuthController* auth_controller) {
375 DCHECK(!IsPreconnecting());
376 if (IsOrphaned())
377 stream_factory_->OnOrphanedJobComplete(this);
378 else
379 request_->OnNeedsProxyAuth(
380 this, response, server_ssl_config_, proxy_info_, auth_controller);
381 // |this| may be deleted after this call.
384 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
385 SSLCertRequestInfo* cert_info) {
386 DCHECK(!IsPreconnecting());
387 if (IsOrphaned())
388 stream_factory_->OnOrphanedJobComplete(this);
389 else
390 request_->OnNeedsClientAuth(this, server_ssl_config_, cert_info);
391 // |this| may be deleted after this call.
394 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
395 const HttpResponseInfo& response_info,
396 HttpStream* stream) {
397 DCHECK(!IsPreconnecting());
398 if (IsOrphaned())
399 stream_factory_->OnOrphanedJobComplete(this);
400 else
401 request_->OnHttpsProxyTunnelResponse(
402 this, response_info, server_ssl_config_, proxy_info_, stream);
403 // |this| may be deleted after this call.
406 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
407 DCHECK(!request_);
408 if (new_spdy_session_.get()) {
409 stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
410 spdy_session_direct_,
411 server_ssl_config_,
412 proxy_info_,
413 was_npn_negotiated(),
414 protocol_negotiated(),
415 using_spdy(),
416 net_log_);
418 stream_factory_->OnPreconnectsComplete(this);
419 // |this| may be deleted after this call.
422 // static
423 int HttpStreamFactoryImpl::Job::OnHostResolution(
424 SpdySessionPool* spdy_session_pool,
425 const SpdySessionKey& spdy_session_key,
426 const AddressList& addresses,
427 const BoundNetLog& net_log) {
428 // It is OK to dereference spdy_session_pool, because the
429 // ClientSocketPoolManager will be destroyed in the same callback that
430 // destroys the SpdySessionPool.
431 return
432 spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
433 ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
436 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
437 RunLoop(result);
440 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
441 result = DoLoop(result);
443 if (result == ERR_IO_PENDING)
444 return result;
446 // If there was an error, we should have already resumed the |waiting_job_|,
447 // if there was one.
448 DCHECK(result == OK || waiting_job_ == NULL);
450 if (IsPreconnecting()) {
451 base::MessageLoop::current()->PostTask(
452 FROM_HERE,
453 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
454 ptr_factory_.GetWeakPtr()));
455 return ERR_IO_PENDING;
458 if (IsCertificateError(result)) {
459 // Retrieve SSL information from the socket.
460 GetSSLInfo();
462 next_state_ = STATE_WAITING_USER_ACTION;
463 base::MessageLoop::current()->PostTask(
464 FROM_HERE,
465 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
466 ptr_factory_.GetWeakPtr(), result, ssl_info_));
467 return ERR_IO_PENDING;
470 switch (result) {
471 case ERR_PROXY_AUTH_REQUESTED: {
472 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
473 connection_.get() != NULL);
474 if (!connection_.get())
475 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
476 CHECK(connection_->socket());
477 CHECK(establishing_tunnel_);
479 next_state_ = STATE_WAITING_USER_ACTION;
480 ProxyClientSocket* proxy_socket =
481 static_cast<ProxyClientSocket*>(connection_->socket());
482 base::MessageLoop::current()->PostTask(
483 FROM_HERE,
484 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
485 *proxy_socket->GetConnectResponseInfo(),
486 proxy_socket->GetAuthController()));
487 return ERR_IO_PENDING;
490 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
491 base::MessageLoop::current()->PostTask(
492 FROM_HERE,
493 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
494 connection_->ssl_error_response_info().cert_request_info));
495 return ERR_IO_PENDING;
497 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
498 DCHECK(connection_.get());
499 DCHECK(connection_->socket());
500 DCHECK(establishing_tunnel_);
502 ProxyClientSocket* proxy_socket =
503 static_cast<ProxyClientSocket*>(connection_->socket());
504 base::MessageLoop::current()->PostTask(
505 FROM_HERE,
506 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
507 ptr_factory_.GetWeakPtr(),
508 *proxy_socket->GetConnectResponseInfo(),
509 proxy_socket->CreateConnectResponseStream()));
510 return ERR_IO_PENDING;
513 case OK:
514 job_status_ = STATUS_SUCCEEDED;
515 MaybeMarkAlternateProtocolBroken();
516 next_state_ = STATE_DONE;
517 if (new_spdy_session_.get()) {
518 base::MessageLoop::current()->PostTask(
519 FROM_HERE,
520 base::Bind(&Job::OnNewSpdySessionReadyCallback,
521 ptr_factory_.GetWeakPtr()));
522 } else if (stream_factory_->for_websockets_) {
523 DCHECK(websocket_stream_);
524 base::MessageLoop::current()->PostTask(
525 FROM_HERE,
526 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
527 ptr_factory_.GetWeakPtr()));
528 } else {
529 DCHECK(stream_.get());
530 base::MessageLoop::current()->PostTask(
531 FROM_HERE,
532 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
534 return ERR_IO_PENDING;
536 default:
537 if (job_status_ != STATUS_BROKEN) {
538 DCHECK_EQ(STATUS_RUNNING, job_status_);
539 job_status_ = STATUS_FAILED;
540 MaybeMarkAlternateProtocolBroken();
542 base::MessageLoop::current()->PostTask(
543 FROM_HERE,
544 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
545 result));
546 return ERR_IO_PENDING;
550 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
551 DCHECK_NE(next_state_, STATE_NONE);
552 int rv = result;
553 do {
554 State state = next_state_;
555 next_state_ = STATE_NONE;
556 switch (state) {
557 case STATE_START:
558 DCHECK_EQ(OK, rv);
559 rv = DoStart();
560 break;
561 case STATE_RESOLVE_PROXY:
562 DCHECK_EQ(OK, rv);
563 rv = DoResolveProxy();
564 break;
565 case STATE_RESOLVE_PROXY_COMPLETE:
566 rv = DoResolveProxyComplete(rv);
567 break;
568 case STATE_WAIT_FOR_JOB:
569 DCHECK_EQ(OK, rv);
570 rv = DoWaitForJob();
571 break;
572 case STATE_WAIT_FOR_JOB_COMPLETE:
573 rv = DoWaitForJobComplete(rv);
574 break;
575 case STATE_INIT_CONNECTION:
576 DCHECK_EQ(OK, rv);
577 rv = DoInitConnection();
578 break;
579 case STATE_INIT_CONNECTION_COMPLETE:
580 rv = DoInitConnectionComplete(rv);
581 break;
582 case STATE_WAITING_USER_ACTION:
583 rv = DoWaitingUserAction(rv);
584 break;
585 case STATE_RESTART_TUNNEL_AUTH:
586 DCHECK_EQ(OK, rv);
587 rv = DoRestartTunnelAuth();
588 break;
589 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
590 rv = DoRestartTunnelAuthComplete(rv);
591 break;
592 case STATE_CREATE_STREAM:
593 DCHECK_EQ(OK, rv);
594 rv = DoCreateStream();
595 break;
596 case STATE_CREATE_STREAM_COMPLETE:
597 rv = DoCreateStreamComplete(rv);
598 break;
599 default:
600 NOTREACHED() << "bad state";
601 rv = ERR_FAILED;
602 break;
604 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
605 return rv;
608 int HttpStreamFactoryImpl::Job::StartInternal() {
609 CHECK_EQ(STATE_NONE, next_state_);
610 next_state_ = STATE_START;
611 int rv = RunLoop(OK);
612 DCHECK_EQ(ERR_IO_PENDING, rv);
613 return rv;
616 int HttpStreamFactoryImpl::Job::DoStart() {
617 origin_ = HostPortPair::FromURL(request_info_.url);
618 origin_url_ = stream_factory_->ApplyHostMappingRules(
619 request_info_.url, &origin_);
621 net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB,
622 base::Bind(&NetLogHttpStreamJobCallback,
623 &request_info_.url, &origin_url_,
624 priority_));
626 // Don't connect to restricted ports.
627 bool is_port_allowed = IsPortAllowedByDefault(origin_.port());
628 if (request_info_.url.SchemeIs("ftp")) {
629 // Never share connection with other jobs for FTP requests.
630 DCHECK(!waiting_job_);
632 is_port_allowed = IsPortAllowedByFtp(origin_.port());
634 if (!is_port_allowed && !IsPortAllowedByOverride(origin_.port())) {
635 if (waiting_job_) {
636 waiting_job_->Resume(this);
637 waiting_job_ = NULL;
639 return ERR_UNSAFE_PORT;
642 next_state_ = STATE_RESOLVE_PROXY;
643 return OK;
646 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
647 DCHECK(!pac_request_);
648 DCHECK(session_);
650 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
652 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
653 proxy_info_.UseDirect();
654 return OK;
657 return session_->proxy_service()->ResolveProxy(
658 request_info_.url, request_info_.load_flags, &proxy_info_, io_callback_,
659 &pac_request_, session_->network_delegate(), net_log_);
662 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
663 pac_request_ = NULL;
665 if (result == OK) {
666 // Remove unsupported proxies from the list.
667 proxy_info_.RemoveProxiesWithoutScheme(
668 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_QUIC |
669 ProxyServer::SCHEME_HTTP | ProxyServer::SCHEME_HTTPS |
670 ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
672 if (proxy_info_.is_empty()) {
673 // No proxies/direct to choose from. This happens when we don't support
674 // any of the proxies in the returned list.
675 result = ERR_NO_SUPPORTED_PROXIES;
676 } else if (using_quic_ &&
677 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
678 // QUIC can not be spoken to non-QUIC proxies. This error should not be
679 // user visible, because the non-alternate job should be resumed.
680 result = ERR_NO_SUPPORTED_PROXIES;
684 if (result != OK) {
685 if (waiting_job_) {
686 waiting_job_->Resume(this);
687 waiting_job_ = NULL;
689 return result;
692 if (blocking_job_)
693 next_state_ = STATE_WAIT_FOR_JOB;
694 else
695 next_state_ = STATE_INIT_CONNECTION;
696 return OK;
699 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
700 bool rv = session_->params().force_spdy_always &&
701 session_->params().force_spdy_over_ssl;
702 return rv && !session_->HasSpdyExclusion(origin_);
705 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
706 bool rv = session_->params().force_spdy_always &&
707 !session_->params().force_spdy_over_ssl;
708 return rv && !session_->HasSpdyExclusion(origin_);
711 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
712 return session_->params().enable_quic &&
713 session_->params().origin_to_force_quic_on.Equals(origin_) &&
714 proxy_info_.is_direct();
717 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
718 DCHECK(blocking_job_);
719 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
720 return ERR_IO_PENDING;
723 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
724 DCHECK(!blocking_job_);
725 DCHECK_EQ(OK, result);
726 next_state_ = STATE_INIT_CONNECTION;
727 return OK;
730 int HttpStreamFactoryImpl::Job::DoInitConnection() {
731 DCHECK(!blocking_job_);
732 DCHECK(!connection_->is_initialized());
733 DCHECK(proxy_info_.proxy_server().is_valid());
734 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
736 using_ssl_ = request_info_.url.SchemeIs("https") ||
737 request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
738 using_spdy_ = false;
740 if (ShouldForceQuic())
741 using_quic_ = true;
743 if (proxy_info_.is_quic())
744 using_quic_ = true;
746 if (using_quic_) {
747 DCHECK(session_->params().enable_quic);
748 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
749 NOTREACHED();
750 // TODO(rch): support QUIC proxies for HTTPS urls.
751 return ERR_NOT_IMPLEMENTED;
753 HostPortPair destination = proxy_info_.is_quic() ?
754 proxy_info_.proxy_server().host_port_pair() : origin_;
755 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
756 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
757 int rv = quic_request_.Request(
758 destination, secure_quic, request_info_.privacy_mode,
759 request_info_.method, net_log_, io_callback_);
760 if (rv == OK) {
761 using_existing_quic_session_ = true;
762 } else {
763 // OK, there's no available QUIC session. Let |waiting_job_| resume
764 // if it's paused.
765 if (waiting_job_) {
766 waiting_job_->Resume(this);
767 waiting_job_ = NULL;
770 return rv;
773 // Check first if we have a spdy session for this group. If so, then go
774 // straight to using that.
775 SpdySessionKey spdy_session_key = GetSpdySessionKey();
776 base::WeakPtr<SpdySession> spdy_session =
777 session_->spdy_session_pool()->FindAvailableSession(
778 spdy_session_key, net_log_);
779 if (spdy_session && CanUseExistingSpdySession()) {
780 // If we're preconnecting, but we already have a SpdySession, we don't
781 // actually need to preconnect any sockets, so we're done.
782 if (IsPreconnecting())
783 return OK;
784 using_spdy_ = true;
785 next_state_ = STATE_CREATE_STREAM;
786 existing_spdy_session_ = spdy_session;
787 return OK;
788 } else if (request_ && !request_->HasSpdySessionKey() &&
789 (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
790 // Update the spdy session key for the request that launched this job.
791 request_->SetSpdySessionKey(spdy_session_key);
794 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
795 // paused.
797 if (waiting_job_) {
798 waiting_job_->Resume(this);
799 waiting_job_ = NULL;
802 if (proxy_info_.is_http() || proxy_info_.is_https())
803 establishing_tunnel_ = using_ssl_;
805 bool want_spdy_over_npn = original_url_ != NULL;
807 if (proxy_info_.is_https()) {
808 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
809 &proxy_ssl_config_,
810 true /* is a proxy server */);
811 // Disable revocation checking for HTTPS proxies since the revocation
812 // requests are probably going to need to go through the proxy too.
813 proxy_ssl_config_.rev_checking_enabled = false;
815 if (using_ssl_) {
816 InitSSLConfig(origin_, &server_ssl_config_,
817 false /* not a proxy server */);
820 if (IsPreconnecting()) {
821 DCHECK(!stream_factory_->for_websockets_);
822 return PreconnectSocketsForHttpRequest(
823 origin_url_,
824 request_info_.extra_headers,
825 request_info_.load_flags,
826 priority_,
827 session_,
828 proxy_info_,
829 ShouldForceSpdySSL(),
830 want_spdy_over_npn,
831 server_ssl_config_,
832 proxy_ssl_config_,
833 request_info_.privacy_mode,
834 net_log_,
835 num_streams_);
838 // If we can't use a SPDY session, don't both checking for one after
839 // the hostname is resolved.
840 OnHostResolutionCallback resolution_callback = CanUseExistingSpdySession() ?
841 base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
842 GetSpdySessionKey()) :
843 OnHostResolutionCallback();
844 if (stream_factory_->for_websockets_) {
845 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
846 SSLConfig websocket_server_ssl_config = server_ssl_config_;
847 websocket_server_ssl_config.next_protos.clear();
848 return InitSocketHandleForWebSocketRequest(
849 origin_url_, request_info_.extra_headers, request_info_.load_flags,
850 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
851 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
852 request_info_.privacy_mode, net_log_,
853 connection_.get(), resolution_callback, io_callback_);
856 return InitSocketHandleForHttpRequest(
857 origin_url_, request_info_.extra_headers, request_info_.load_flags,
858 priority_, session_, proxy_info_, ShouldForceSpdySSL(),
859 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
860 request_info_.privacy_mode, net_log_,
861 connection_.get(), resolution_callback, io_callback_);
864 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
865 if (IsPreconnecting()) {
866 if (using_quic_)
867 return result;
868 DCHECK_EQ(OK, result);
869 return OK;
872 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
873 // We found a SPDY connection after resolving the host. This is
874 // probably an IP pooled connection.
875 SpdySessionKey spdy_session_key = GetSpdySessionKey();
876 existing_spdy_session_ =
877 session_->spdy_session_pool()->FindAvailableSession(
878 spdy_session_key, net_log_);
879 if (existing_spdy_session_) {
880 using_spdy_ = true;
881 next_state_ = STATE_CREATE_STREAM;
882 } else {
883 // It is possible that the spdy session no longer exists.
884 ReturnToStateInitConnection(true /* close connection */);
886 return OK;
889 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
890 // errors, such as ignoring certificate errors for Alternate-Protocol.
891 if (result < 0 && waiting_job_) {
892 waiting_job_->Resume(this);
893 waiting_job_ = NULL;
896 // |result| may be the result of any of the stacked pools. The following
897 // logic is used when determining how to interpret an error.
898 // If |result| < 0:
899 // and connection_->socket() != NULL, then the SSL handshake ran and it
900 // is a potentially recoverable error.
901 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
902 // then the SSL handshake ran with an unrecoverable error.
903 // otherwise, the error came from one of the other pools.
904 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
905 connection_->is_ssl_error());
907 if (ssl_started && (result == OK || IsCertificateError(result))) {
908 if (using_quic_ && result == OK) {
909 was_npn_negotiated_ = true;
910 NextProto protocol_negotiated =
911 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
912 protocol_negotiated_ = protocol_negotiated;
913 } else {
914 SSLClientSocket* ssl_socket =
915 static_cast<SSLClientSocket*>(connection_->socket());
916 if (ssl_socket->WasNpnNegotiated()) {
917 was_npn_negotiated_ = true;
918 std::string proto;
919 SSLClientSocket::NextProtoStatus status =
920 ssl_socket->GetNextProto(&proto);
921 NextProto protocol_negotiated =
922 SSLClientSocket::NextProtoFromString(proto);
923 protocol_negotiated_ = protocol_negotiated;
924 net_log_.AddEvent(
925 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
926 base::Bind(&NetLogHttpStreamProtoCallback,
927 status, &proto));
928 if (ssl_socket->was_spdy_negotiated())
929 SwitchToSpdyMode();
931 if (ShouldForceSpdySSL())
932 SwitchToSpdyMode();
934 } else if (proxy_info_.is_https() && connection_->socket() &&
935 result == OK) {
936 ProxyClientSocket* proxy_socket =
937 static_cast<ProxyClientSocket*>(connection_->socket());
938 if (proxy_socket->IsUsingSpdy()) {
939 was_npn_negotiated_ = true;
940 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
941 SwitchToSpdyMode();
945 // We may be using spdy without SSL
946 if (ShouldForceSpdyWithoutSSL())
947 SwitchToSpdyMode();
949 if (result == ERR_PROXY_AUTH_REQUESTED ||
950 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
951 DCHECK(!ssl_started);
952 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
953 // SSL socket, but there was an error before that could happen. This
954 // puts the in progress HttpProxy socket into |connection_| in order to
955 // complete the auth (or read the response body). The tunnel restart code
956 // is careful to remove it before returning control to the rest of this
957 // class.
958 connection_.reset(connection_->release_pending_http_proxy_connection());
959 return result;
962 if (!ssl_started && result < 0 && original_url_.get()) {
963 job_status_ = STATUS_BROKEN;
964 MaybeMarkAlternateProtocolBroken();
965 return result;
968 if (using_quic_) {
969 if (result < 0) {
970 job_status_ = STATUS_BROKEN;
971 MaybeMarkAlternateProtocolBroken();
972 return result;
974 stream_ = quic_request_.ReleaseStream();
975 next_state_ = STATE_NONE;
976 return OK;
979 if (result < 0 && !ssl_started)
980 return ReconsiderProxyAfterError(result);
981 establishing_tunnel_ = false;
983 if (connection_->socket()) {
984 LogHttpConnectedMetrics(*connection_);
986 // We officially have a new connection. Record the type.
987 if (!connection_->is_reused()) {
988 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
989 UpdateConnectionTypeHistograms(type);
993 // Handle SSL errors below.
994 if (using_ssl_) {
995 DCHECK(ssl_started);
996 if (IsCertificateError(result)) {
997 if (using_spdy_ && original_url_.get() &&
998 original_url_->SchemeIs("http")) {
999 // We ignore certificate errors for http over spdy.
1000 spdy_certificate_error_ = result;
1001 result = OK;
1002 } else {
1003 result = HandleCertificateError(result);
1004 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1005 ReturnToStateInitConnection(true /* close connection */);
1006 return result;
1010 if (result < 0)
1011 return result;
1014 next_state_ = STATE_CREATE_STREAM;
1015 return OK;
1018 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1019 // This state indicates that the stream request is in a partially
1020 // completed state, and we've called back to the delegate for more
1021 // information.
1023 // We're always waiting here for the delegate to call us back.
1024 return ERR_IO_PENDING;
1027 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1028 base::WeakPtr<SpdySession> session, bool direct) {
1029 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1030 // implemented.
1031 if (stream_factory_->for_websockets_)
1032 return ERR_NOT_IMPLEMENTED;
1034 // TODO(willchan): Delete this code, because eventually, the
1035 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1036 // will know when SpdySessions become available.
1038 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1039 stream_.reset(new SpdyHttpStream(session, use_relative_url));
1040 return OK;
1043 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1044 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1046 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1048 // We only set the socket motivation if we're the first to use
1049 // this socket. Is there a race for two SPDY requests? We really
1050 // need to plumb this through to the connect level.
1051 if (connection_->socket() && !connection_->is_reused())
1052 SetSocketMotivation();
1054 if (!using_spdy_) {
1055 // We may get ftp scheme when fetching ftp resources through proxy.
1056 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1057 (request_info_.url.SchemeIs("http") ||
1058 request_info_.url.SchemeIs("ftp"));
1059 if (stream_factory_->for_websockets_) {
1060 DCHECK(request_);
1061 DCHECK(request_->websocket_handshake_stream_create_helper());
1062 websocket_stream_.reset(
1063 request_->websocket_handshake_stream_create_helper()
1064 ->CreateBasicStream(connection_.Pass(), using_proxy));
1065 } else {
1066 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1068 return OK;
1071 CHECK(!stream_.get());
1073 bool direct = true;
1074 const ProxyServer& proxy_server = proxy_info_.proxy_server();
1075 PrivacyMode privacy_mode = request_info_.privacy_mode;
1076 if (IsHttpsProxyAndHttpUrl())
1077 direct = false;
1079 if (existing_spdy_session_.get()) {
1080 // We picked up an existing session, so we don't need our socket.
1081 if (connection_->socket())
1082 connection_->socket()->Disconnect();
1083 connection_->Reset();
1085 int set_result = SetSpdyHttpStream(existing_spdy_session_, direct);
1086 existing_spdy_session_.reset();
1087 return set_result;
1090 SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1091 if (IsHttpsProxyAndHttpUrl()) {
1092 // If we don't have a direct SPDY session, and we're using an HTTPS
1093 // proxy, then we might have a SPDY session to the proxy.
1094 // We never use privacy mode for connection to proxy server.
1095 spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1096 ProxyServer::Direct(),
1097 PRIVACY_MODE_DISABLED);
1100 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1101 base::WeakPtr<SpdySession> spdy_session =
1102 spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1104 if (spdy_session) {
1105 return SetSpdyHttpStream(spdy_session, direct);
1108 spdy_session =
1109 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1110 connection_.Pass(),
1111 net_log_,
1112 spdy_certificate_error_,
1113 using_ssl_);
1114 if (!spdy_session->HasAcceptableTransportSecurity()) {
1115 spdy_session->CloseSessionOnError(
1116 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1117 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1120 new_spdy_session_ = spdy_session;
1121 spdy_session_direct_ = direct;
1122 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1123 base::WeakPtr<HttpServerProperties> http_server_properties =
1124 session_->http_server_properties();
1125 if (http_server_properties)
1126 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1128 // Create a SpdyHttpStream attached to the session;
1129 // OnNewSpdySessionReadyCallback is not called until an event loop
1130 // iteration later, so if the SpdySession is closed between then, allow
1131 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1132 // bubble up to the request.
1133 return SetSpdyHttpStream(new_spdy_session_, spdy_session_direct_);
1136 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1137 if (result < 0)
1138 return result;
1140 session_->proxy_service()->ReportSuccess(proxy_info_,
1141 session_->network_delegate());
1142 next_state_ = STATE_NONE;
1143 return OK;
1146 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1147 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1148 ProxyClientSocket* proxy_socket =
1149 static_cast<ProxyClientSocket*>(connection_->socket());
1150 return proxy_socket->RestartWithAuth(io_callback_);
1153 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1154 if (result == ERR_PROXY_AUTH_REQUESTED)
1155 return result;
1157 if (result == OK) {
1158 // Now that we've got the HttpProxyClientSocket connected. We have
1159 // to release it as an idle socket into the pool and start the connection
1160 // process from the beginning. Trying to pass it in with the
1161 // SSLSocketParams might cause a deadlock since params are dispatched
1162 // interchangeably. This request won't necessarily get this http proxy
1163 // socket, but there will be forward progress.
1164 establishing_tunnel_ = false;
1165 ReturnToStateInitConnection(false /* do not close connection */);
1166 return OK;
1169 return ReconsiderProxyAfterError(result);
1172 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1173 bool close_connection) {
1174 if (close_connection && connection_->socket())
1175 connection_->socket()->Disconnect();
1176 connection_->Reset();
1178 if (request_)
1179 request_->RemoveRequestFromSpdySessionRequestMap();
1181 next_state_ = STATE_INIT_CONNECTION;
1184 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1185 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1186 connection_->socket()->SetSubresourceSpeculation();
1187 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1188 connection_->socket()->SetOmniboxSpeculation();
1189 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1192 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1193 if (!proxy_info_.is_https())
1194 return false;
1195 if (original_url_.get()) {
1196 // We currently only support Alternate-Protocol where the original scheme
1197 // is http.
1198 DCHECK(original_url_->SchemeIs("http"));
1199 return original_url_->SchemeIs("http");
1201 return request_info_.url.SchemeIs("http");
1204 // Sets several fields of ssl_config for the given origin_server based on the
1205 // proxy info and other factors.
1206 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1207 const HostPortPair& origin_server,
1208 SSLConfig* ssl_config,
1209 bool is_proxy) const {
1210 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1211 // When connecting through an HTTPS proxy, disable TLS False Start so
1212 // that client authentication errors can be distinguished between those
1213 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1214 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1215 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1216 // TODO(rch): This assumes that the HTTPS proxy will only request a
1217 // client certificate during the initial handshake.
1218 // http://crbug.com/59292
1219 ssl_config->false_start_enabled = false;
1222 enum {
1223 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1224 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1225 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1226 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1227 FALLBACK_MAX
1230 int fallback = FALLBACK_NONE;
1231 if (ssl_config->version_fallback) {
1232 switch (ssl_config->version_max) {
1233 case SSL_PROTOCOL_VERSION_SSL3:
1234 fallback = FALLBACK_SSL3;
1235 break;
1236 case SSL_PROTOCOL_VERSION_TLS1:
1237 fallback = FALLBACK_TLS1;
1238 break;
1239 case SSL_PROTOCOL_VERSION_TLS1_1:
1240 fallback = FALLBACK_TLS1_1;
1241 break;
1244 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1245 fallback, FALLBACK_MAX);
1247 // We also wish to measure the amount of fallback connections for a host that
1248 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1249 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1250 // caused by network middleware rather than buggy HTTPS servers.
1251 const std::string& host = origin_server.host();
1252 if (!is_proxy &&
1253 host.size() >= 10 &&
1254 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1255 (host.size() == 10 || host[host.size()-11] == '.')) {
1256 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1257 fallback, FALLBACK_MAX);
1260 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1261 ssl_config->verify_ev_cert = true;
1263 // Disable Channel ID if privacy mode is enabled.
1264 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1265 ssl_config->channel_id_enabled = false;
1269 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1270 DCHECK(!pac_request_);
1271 DCHECK(session_);
1273 // A failure to resolve the hostname or any error related to establishing a
1274 // TCP connection could be grounds for trying a new proxy configuration.
1276 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1277 // to proxy servers. The hostname in those URLs might fail to resolve if we
1278 // are still using a non-proxy config. We need to check if a proxy config
1279 // now exists that corresponds to a proxy server that could load the URL.
1281 switch (error) {
1282 case ERR_PROXY_CONNECTION_FAILED:
1283 case ERR_NAME_NOT_RESOLVED:
1284 case ERR_INTERNET_DISCONNECTED:
1285 case ERR_ADDRESS_UNREACHABLE:
1286 case ERR_CONNECTION_CLOSED:
1287 case ERR_CONNECTION_TIMED_OUT:
1288 case ERR_CONNECTION_RESET:
1289 case ERR_CONNECTION_REFUSED:
1290 case ERR_CONNECTION_ABORTED:
1291 case ERR_TIMED_OUT:
1292 case ERR_TUNNEL_CONNECTION_FAILED:
1293 case ERR_SOCKS_CONNECTION_FAILED:
1294 // This can happen in the case of trying to talk to a proxy using SSL, and
1295 // ending up talking to a captive portal that supports SSL instead.
1296 case ERR_PROXY_CERTIFICATE_INVALID:
1297 // This can happen when trying to talk SSL to a non-SSL server (Like a
1298 // captive portal).
1299 case ERR_SSL_PROTOCOL_ERROR:
1300 break;
1301 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1302 // Remap the SOCKS-specific "host unreachable" error to a more
1303 // generic error code (this way consumers like the link doctor
1304 // know to substitute their error page).
1306 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1307 // differentiate between a proxy-side "host not found" versus a proxy-side
1308 // "address unreachable" error, and will report both of these failures as
1309 // ERR_ADDRESS_UNREACHABLE.
1310 return ERR_ADDRESS_UNREACHABLE;
1311 default:
1312 return error;
1315 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1316 return error;
1319 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1320 session_->ssl_client_auth_cache()->Remove(
1321 proxy_info_.proxy_server().host_port_pair());
1324 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1325 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1326 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1327 if (rv == OK || rv == ERR_IO_PENDING) {
1328 // If the error was during connection setup, there is no socket to
1329 // disconnect.
1330 if (connection_->socket())
1331 connection_->socket()->Disconnect();
1332 connection_->Reset();
1333 if (request_)
1334 request_->RemoveRequestFromSpdySessionRequestMap();
1335 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1336 } else {
1337 // If ReconsiderProxyAfterError() failed synchronously, it means
1338 // there was nothing left to fall-back to, so fail the transaction
1339 // with the last connection error we got.
1340 // TODO(eroman): This is a confusing contract, make it more obvious.
1341 rv = error;
1344 return rv;
1347 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1348 DCHECK(using_ssl_);
1349 DCHECK(IsCertificateError(error));
1351 SSLClientSocket* ssl_socket =
1352 static_cast<SSLClientSocket*>(connection_->socket());
1353 ssl_socket->GetSSLInfo(&ssl_info_);
1355 // Add the bad certificate to the set of allowed certificates in the
1356 // SSL config object. This data structure will be consulted after calling
1357 // RestartIgnoringLastError(). And the user will be asked interactively
1358 // before RestartIgnoringLastError() is ever called.
1359 SSLConfig::CertAndStatus bad_cert;
1361 // |ssl_info_.cert| may be NULL if we failed to create
1362 // X509Certificate for whatever reason, but normally it shouldn't
1363 // happen, unless this code is used inside sandbox.
1364 if (ssl_info_.cert.get() == NULL ||
1365 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1366 &bad_cert.der_cert)) {
1367 return error;
1369 bad_cert.cert_status = ssl_info_.cert_status;
1370 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1372 int load_flags = request_info_.load_flags;
1373 if (session_->params().ignore_certificate_errors)
1374 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1375 if (ssl_socket->IgnoreCertError(error, load_flags))
1376 return OK;
1377 return error;
1380 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1381 if (HttpStreamFactory::spdy_enabled())
1382 using_spdy_ = true;
1385 // static
1386 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1387 const ClientSocketHandle& handle) {
1388 UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
1389 ClientSocketHandle::NUM_TYPES);
1391 switch (handle.reuse_type()) {
1392 case ClientSocketHandle::UNUSED:
1393 UMA_HISTOGRAM_CUSTOM_TIMES("Net.HttpConnectionLatency",
1394 handle.setup_time(),
1395 base::TimeDelta::FromMilliseconds(1),
1396 base::TimeDelta::FromMinutes(10),
1397 100);
1398 break;
1399 case ClientSocketHandle::UNUSED_IDLE:
1400 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_UnusedSocket",
1401 handle.idle_time(),
1402 base::TimeDelta::FromMilliseconds(1),
1403 base::TimeDelta::FromMinutes(6),
1404 100);
1405 break;
1406 case ClientSocketHandle::REUSED_IDLE:
1407 UMA_HISTOGRAM_CUSTOM_TIMES("Net.SocketIdleTimeBeforeNextUse_ReusedSocket",
1408 handle.idle_time(),
1409 base::TimeDelta::FromMilliseconds(1),
1410 base::TimeDelta::FromMinutes(6),
1411 100);
1412 break;
1413 default:
1414 NOTREACHED();
1415 break;
1419 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1420 DCHECK_GE(num_streams_, 0);
1421 return num_streams_ > 0;
1424 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1425 return !IsPreconnecting() && !request_;
1428 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1429 if (using_existing_quic_session_) {
1430 // If an existing session was used, then no TCP connection was
1431 // started.
1432 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE);
1433 } else if (original_url_) {
1434 // This job was the alternate protocol job, and hence won the race.
1435 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE);
1436 } else {
1437 // This job was the normal job, and hence the alternate protocol job lost
1438 // the race.
1439 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE);
1443 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1444 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1445 other_job_status_ = job.job_status_;
1446 MaybeMarkAlternateProtocolBroken();
1449 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1450 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1451 return;
1453 bool is_alternate_protocol_job = original_url_.get() != NULL;
1454 if (is_alternate_protocol_job) {
1455 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1456 HistogramBrokenAlternateProtocolLocation(
1457 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1458 session_->http_server_properties()->SetBrokenAlternateProtocol(
1459 HostPortPair::FromURL(*original_url_));
1461 return;
1464 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1465 HistogramBrokenAlternateProtocolLocation(
1466 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1467 session_->http_server_properties()->SetBrokenAlternateProtocol(
1468 HostPortPair::FromURL(request_info_.url));
1472 } // namespace net