Supervised user whitelists: Cleanup
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.cc
blob5843d4c342ab972823a3d643d5155ca92d697fca
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/http/http_stream_factory_impl_job.h"
7 #include <algorithm>
8 #include <string>
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/logging.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/profiler/scoped_tracker.h"
15 #include "base/stl_util.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h"
19 #include "base/values.h"
20 #include "build/build_config.h"
21 #include "net/base/connection_type_histograms.h"
22 #include "net/base/net_util.h"
23 #include "net/http/http_basic_stream.h"
24 #include "net/http/http_network_session.h"
25 #include "net/http/http_proxy_client_socket.h"
26 #include "net/http/http_proxy_client_socket_pool.h"
27 #include "net/http/http_request_info.h"
28 #include "net/http/http_server_properties.h"
29 #include "net/http/http_stream_factory.h"
30 #include "net/http/http_stream_factory_impl_request.h"
31 #include "net/log/net_log.h"
32 #include "net/quic/quic_http_stream.h"
33 #include "net/socket/client_socket_handle.h"
34 #include "net/socket/client_socket_pool.h"
35 #include "net/socket/client_socket_pool_manager.h"
36 #include "net/socket/socks_client_socket_pool.h"
37 #include "net/socket/ssl_client_socket.h"
38 #include "net/socket/ssl_client_socket_pool.h"
39 #include "net/spdy/spdy_http_stream.h"
40 #include "net/spdy/spdy_session.h"
41 #include "net/spdy/spdy_session_pool.h"
42 #include "net/ssl/ssl_cert_request_info.h"
44 namespace net {
46 // Returns parameters associated with the start of a HTTP stream job.
47 base::Value* NetLogHttpStreamJobCallback(
48 const GURL* original_url,
49 const GURL* url,
50 const AlternativeService* alternative_service,
51 RequestPriority priority,
52 NetLogCaptureMode /* capture_mode */) {
53 base::DictionaryValue* dict = new base::DictionaryValue();
54 dict->SetString("original_url", original_url->GetOrigin().spec());
55 dict->SetString("url", url->GetOrigin().spec());
56 dict->SetString("alternative_service", alternative_service->ToString());
57 dict->SetString("priority", RequestPriorityToString(priority));
58 return dict;
61 // Returns parameters associated with the Proto (with NPN negotiation) of a HTTP
62 // stream.
63 base::Value* NetLogHttpStreamProtoCallback(
64 const SSLClientSocket::NextProtoStatus status,
65 const std::string* proto,
66 NetLogCaptureMode /* capture_mode */) {
67 base::DictionaryValue* dict = new base::DictionaryValue();
69 dict->SetString("next_proto_status",
70 SSLClientSocket::NextProtoStatusToString(status));
71 dict->SetString("proto", *proto);
72 return dict;
75 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
76 HttpNetworkSession* session,
77 const HttpRequestInfo& request_info,
78 RequestPriority priority,
79 const SSLConfig& server_ssl_config,
80 const SSLConfig& proxy_ssl_config,
81 NetLog* net_log)
82 : request_(NULL),
83 request_info_(request_info),
84 priority_(priority),
85 server_ssl_config_(server_ssl_config),
86 proxy_ssl_config_(proxy_ssl_config),
87 net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
88 io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
89 connection_(new ClientSocketHandle),
90 session_(session),
91 stream_factory_(stream_factory),
92 next_state_(STATE_NONE),
93 pac_request_(NULL),
94 blocking_job_(NULL),
95 waiting_job_(NULL),
96 using_ssl_(false),
97 using_spdy_(false),
98 using_quic_(false),
99 quic_request_(session_->quic_stream_factory()),
100 using_existing_quic_session_(false),
101 spdy_certificate_error_(OK),
102 establishing_tunnel_(false),
103 was_npn_negotiated_(false),
104 protocol_negotiated_(kProtoUnknown),
105 num_streams_(0),
106 spdy_session_direct_(false),
107 job_status_(STATUS_RUNNING),
108 other_job_status_(STATUS_RUNNING),
109 ptr_factory_(this) {
110 DCHECK(stream_factory);
111 DCHECK(session);
114 HttpStreamFactoryImpl::Job::~Job() {
115 net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
117 // When we're in a partially constructed state, waiting for the user to
118 // provide certificate handling information or authentication, we can't reuse
119 // this stream at all.
120 if (next_state_ == STATE_WAITING_USER_ACTION) {
121 connection_->socket()->Disconnect();
122 connection_.reset();
125 if (pac_request_)
126 session_->proxy_service()->CancelPacRequest(pac_request_);
128 // The stream could be in a partial state. It is not reusable.
129 if (stream_.get() && next_state_ != STATE_DONE)
130 stream_->Close(true /* not reusable */);
133 void HttpStreamFactoryImpl::Job::Start(Request* request) {
134 DCHECK(request);
135 request_ = request;
136 StartInternal();
139 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
140 DCHECK_GT(num_streams, 0);
141 base::WeakPtr<HttpServerProperties> http_server_properties =
142 session_->http_server_properties();
143 if (http_server_properties &&
144 http_server_properties->SupportsRequestPriority(
145 HostPortPair::FromURL(request_info_.url))) {
146 num_streams_ = 1;
147 } else {
148 num_streams_ = num_streams;
150 return StartInternal();
153 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
154 const AuthCredentials& credentials) {
155 DCHECK(establishing_tunnel_);
156 next_state_ = STATE_RESTART_TUNNEL_AUTH;
157 stream_.reset();
158 return RunLoop(OK);
161 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
162 switch (next_state_) {
163 case STATE_RESOLVE_PROXY_COMPLETE:
164 return session_->proxy_service()->GetLoadState(pac_request_);
165 case STATE_INIT_CONNECTION_COMPLETE:
166 case STATE_CREATE_STREAM_COMPLETE:
167 return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
168 default:
169 return LOAD_STATE_IDLE;
173 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
174 AlternativeService alternative_service) {
175 DCHECK(!IsAlternate());
176 alternative_service_ = alternative_service;
177 if (alternative_service.protocol == QUIC) {
178 DCHECK(session_->params().enable_quic);
179 using_quic_ = true;
183 void HttpStreamFactoryImpl::Job::WaitFor(Job* job) {
184 DCHECK_EQ(STATE_NONE, next_state_);
185 DCHECK_EQ(STATE_NONE, job->next_state_);
186 DCHECK(!blocking_job_);
187 DCHECK(!job->waiting_job_);
188 blocking_job_ = job;
189 job->waiting_job_ = this;
192 void HttpStreamFactoryImpl::Job::Resume(Job* job) {
193 DCHECK_EQ(blocking_job_, job);
194 blocking_job_ = NULL;
196 // We know we're blocked if the next_state_ is STATE_WAIT_FOR_JOB_COMPLETE.
197 // Unblock |this|.
198 if (next_state_ == STATE_WAIT_FOR_JOB_COMPLETE) {
199 base::MessageLoop::current()->PostTask(
200 FROM_HERE,
201 base::Bind(&HttpStreamFactoryImpl::Job::OnIOComplete,
202 ptr_factory_.GetWeakPtr(), OK));
206 void HttpStreamFactoryImpl::Job::Orphan(const Request* request) {
207 DCHECK_EQ(request_, request);
208 request_ = NULL;
209 if (blocking_job_) {
210 // We've been orphaned, but there's a job we're blocked on. Don't bother
211 // racing, just cancel ourself.
212 DCHECK(blocking_job_->waiting_job_);
213 blocking_job_->waiting_job_ = NULL;
214 blocking_job_ = NULL;
215 if (stream_factory_->for_websockets_ &&
216 connection_ && connection_->socket()) {
217 connection_->socket()->Disconnect();
219 stream_factory_->OnOrphanedJobComplete(this);
220 } else if (stream_factory_->for_websockets_) {
221 // We cancel this job because a WebSocketHandshakeStream can't be created
222 // without a WebSocketHandshakeStreamBase::CreateHelper which is stored in
223 // the Request class and isn't accessible from this job.
224 if (connection_ && connection_->socket()) {
225 connection_->socket()->Disconnect();
227 stream_factory_->OnOrphanedJobComplete(this);
231 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) {
232 priority_ = priority;
233 // TODO(akalin): Propagate this to |connection_| and maybe the
234 // preconnect state.
237 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
238 return was_npn_negotiated_;
241 NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const {
242 return protocol_negotiated_;
245 bool HttpStreamFactoryImpl::Job::using_spdy() const {
246 return using_spdy_;
249 const SSLConfig& HttpStreamFactoryImpl::Job::server_ssl_config() const {
250 return server_ssl_config_;
253 const SSLConfig& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
254 return proxy_ssl_config_;
257 const ProxyInfo& HttpStreamFactoryImpl::Job::proxy_info() const {
258 return proxy_info_;
261 void HttpStreamFactoryImpl::Job::GetSSLInfo() {
262 DCHECK(using_ssl_);
263 DCHECK(!establishing_tunnel_);
264 DCHECK(connection_.get() && connection_->socket());
265 SSLClientSocket* ssl_socket =
266 static_cast<SSLClientSocket*>(connection_->socket());
267 ssl_socket->GetSSLInfo(&ssl_info_);
270 SpdySessionKey HttpStreamFactoryImpl::Job::GetSpdySessionKey() const {
271 // In the case that we're using an HTTPS proxy for an HTTP url,
272 // we look for a SPDY session *to* the proxy, instead of to the
273 // origin server.
274 if (IsHttpsProxyAndHttpUrl()) {
275 return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
276 ProxyServer::Direct(), PRIVACY_MODE_DISABLED);
278 return SpdySessionKey(server_, proxy_info_.proxy_server(),
279 request_info_.privacy_mode);
282 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
283 // We need to make sure that if a spdy session was created for
284 // https://somehost/ that we don't use that session for http://somehost:443/.
285 // The only time we can use an existing session is if the request URL is
286 // https (the normal case) or if we're connection to a SPDY proxy.
287 // https://crbug.com/133176
288 // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
289 // working.
290 return origin_url_.SchemeIs("https") ||
291 proxy_info_.proxy_server().is_https() || IsSpdyAlternate();
294 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
295 DCHECK(stream_.get());
296 DCHECK(!IsPreconnecting());
297 DCHECK(!stream_factory_->for_websockets_);
298 if (IsOrphaned()) {
299 stream_factory_->OnOrphanedJobComplete(this);
300 } else {
301 request_->Complete(was_npn_negotiated(),
302 protocol_negotiated(),
303 using_spdy(),
304 net_log_);
305 request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
306 stream_.release());
308 // |this| may be deleted after this call.
311 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
312 DCHECK(websocket_stream_);
313 DCHECK(!IsPreconnecting());
314 DCHECK(stream_factory_->for_websockets_);
315 // An orphaned WebSocket job will be closed immediately and
316 // never be ready.
317 DCHECK(!IsOrphaned());
318 request_->Complete(was_npn_negotiated(),
319 protocol_negotiated(),
320 using_spdy(),
321 net_log_);
322 request_->OnWebSocketHandshakeStreamReady(this,
323 server_ssl_config_,
324 proxy_info_,
325 websocket_stream_.release());
326 // |this| may be deleted after this call.
329 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
330 DCHECK(stream_.get());
331 DCHECK(!IsPreconnecting());
332 DCHECK(using_spdy());
333 // Note: an event loop iteration has passed, so |new_spdy_session_| may be
334 // NULL at this point if the SpdySession closed immediately after creation.
335 base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
336 new_spdy_session_.reset();
338 // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
339 // rather than notifying |request_| directly.
340 if (IsOrphaned()) {
341 if (spdy_session) {
342 stream_factory_->OnNewSpdySessionReady(
343 spdy_session, spdy_session_direct_, server_ssl_config_, proxy_info_,
344 was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_);
346 stream_factory_->OnOrphanedJobComplete(this);
347 } else {
348 request_->OnNewSpdySessionReady(
349 this, stream_.Pass(), spdy_session, spdy_session_direct_);
351 // |this| may be deleted after this call.
354 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result) {
355 DCHECK(!IsPreconnecting());
356 if (IsOrphaned())
357 stream_factory_->OnOrphanedJobComplete(this);
358 else
359 request_->OnStreamFailed(this, result, server_ssl_config_);
360 // |this| may be deleted after this call.
363 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
364 int result, const SSLInfo& ssl_info) {
365 DCHECK(!IsPreconnecting());
366 if (IsOrphaned())
367 stream_factory_->OnOrphanedJobComplete(this);
368 else
369 request_->OnCertificateError(this, result, server_ssl_config_, ssl_info);
370 // |this| may be deleted after this call.
373 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
374 const HttpResponseInfo& response,
375 HttpAuthController* auth_controller) {
376 DCHECK(!IsPreconnecting());
377 if (IsOrphaned())
378 stream_factory_->OnOrphanedJobComplete(this);
379 else
380 request_->OnNeedsProxyAuth(
381 this, response, server_ssl_config_, proxy_info_, auth_controller);
382 // |this| may be deleted after this call.
385 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
386 SSLCertRequestInfo* cert_info) {
387 DCHECK(!IsPreconnecting());
388 if (IsOrphaned())
389 stream_factory_->OnOrphanedJobComplete(this);
390 else
391 request_->OnNeedsClientAuth(this, server_ssl_config_, cert_info);
392 // |this| may be deleted after this call.
395 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
396 const HttpResponseInfo& response_info,
397 HttpStream* stream) {
398 DCHECK(!IsPreconnecting());
399 if (IsOrphaned())
400 stream_factory_->OnOrphanedJobComplete(this);
401 else
402 request_->OnHttpsProxyTunnelResponse(
403 this, response_info, server_ssl_config_, proxy_info_, stream);
404 // |this| may be deleted after this call.
407 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
408 DCHECK(!request_);
409 if (new_spdy_session_.get()) {
410 stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
411 spdy_session_direct_,
412 server_ssl_config_,
413 proxy_info_,
414 was_npn_negotiated(),
415 protocol_negotiated(),
416 using_spdy(),
417 net_log_);
419 stream_factory_->OnPreconnectsComplete(this);
420 // |this| may be deleted after this call.
423 // static
424 int HttpStreamFactoryImpl::Job::OnHostResolution(
425 SpdySessionPool* spdy_session_pool,
426 const SpdySessionKey& spdy_session_key,
427 const AddressList& addresses,
428 const BoundNetLog& net_log) {
429 // It is OK to dereference spdy_session_pool, because the
430 // ClientSocketPoolManager will be destroyed in the same callback that
431 // destroys the SpdySessionPool.
432 return
433 spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
434 ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
437 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
438 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455884 is fixed.
439 tracked_objects::ScopedTracker tracking_profile(
440 FROM_HERE_WITH_EXPLICIT_FUNCTION(
441 "455884 HttpStreamFactoryImpl::Job::OnIOComplete"));
442 RunLoop(result);
445 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
446 result = DoLoop(result);
448 if (result == ERR_IO_PENDING)
449 return result;
451 // If there was an error, we should have already resumed the |waiting_job_|,
452 // if there was one.
453 DCHECK(result == OK || waiting_job_ == NULL);
455 if (IsPreconnecting()) {
456 base::MessageLoop::current()->PostTask(
457 FROM_HERE,
458 base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
459 ptr_factory_.GetWeakPtr()));
460 return ERR_IO_PENDING;
463 if (IsCertificateError(result)) {
464 // Retrieve SSL information from the socket.
465 GetSSLInfo();
467 next_state_ = STATE_WAITING_USER_ACTION;
468 base::MessageLoop::current()->PostTask(
469 FROM_HERE,
470 base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
471 ptr_factory_.GetWeakPtr(), result, ssl_info_));
472 return ERR_IO_PENDING;
475 switch (result) {
476 case ERR_PROXY_AUTH_REQUESTED: {
477 UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
478 connection_.get() != NULL);
479 if (!connection_.get())
480 return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
481 CHECK(connection_->socket());
482 CHECK(establishing_tunnel_);
484 next_state_ = STATE_WAITING_USER_ACTION;
485 ProxyClientSocket* proxy_socket =
486 static_cast<ProxyClientSocket*>(connection_->socket());
487 base::MessageLoop::current()->PostTask(
488 FROM_HERE,
489 base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
490 *proxy_socket->GetConnectResponseInfo(),
491 proxy_socket->GetAuthController()));
492 return ERR_IO_PENDING;
495 case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
496 base::MessageLoop::current()->PostTask(
497 FROM_HERE,
498 base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
499 connection_->ssl_error_response_info().cert_request_info));
500 return ERR_IO_PENDING;
502 case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
503 DCHECK(connection_.get());
504 DCHECK(connection_->socket());
505 DCHECK(establishing_tunnel_);
507 ProxyClientSocket* proxy_socket =
508 static_cast<ProxyClientSocket*>(connection_->socket());
509 base::MessageLoop::current()->PostTask(
510 FROM_HERE,
511 base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
512 ptr_factory_.GetWeakPtr(),
513 *proxy_socket->GetConnectResponseInfo(),
514 proxy_socket->CreateConnectResponseStream()));
515 return ERR_IO_PENDING;
518 case OK:
519 job_status_ = STATUS_SUCCEEDED;
520 MaybeMarkAlternativeServiceBroken();
521 next_state_ = STATE_DONE;
522 if (new_spdy_session_.get()) {
523 base::MessageLoop::current()->PostTask(
524 FROM_HERE,
525 base::Bind(&Job::OnNewSpdySessionReadyCallback,
526 ptr_factory_.GetWeakPtr()));
527 } else if (stream_factory_->for_websockets_) {
528 DCHECK(websocket_stream_);
529 base::MessageLoop::current()->PostTask(
530 FROM_HERE,
531 base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
532 ptr_factory_.GetWeakPtr()));
533 } else {
534 DCHECK(stream_.get());
535 base::MessageLoop::current()->PostTask(
536 FROM_HERE,
537 base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
539 return ERR_IO_PENDING;
541 default:
542 if (job_status_ != STATUS_BROKEN) {
543 DCHECK_EQ(STATUS_RUNNING, job_status_);
544 job_status_ = STATUS_FAILED;
545 MaybeMarkAlternativeServiceBroken();
547 base::MessageLoop::current()->PostTask(
548 FROM_HERE,
549 base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
550 result));
551 return ERR_IO_PENDING;
555 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
556 DCHECK_NE(next_state_, STATE_NONE);
557 int rv = result;
558 do {
559 State state = next_state_;
560 next_state_ = STATE_NONE;
561 switch (state) {
562 case STATE_START:
563 DCHECK_EQ(OK, rv);
564 rv = DoStart();
565 break;
566 case STATE_RESOLVE_PROXY:
567 DCHECK_EQ(OK, rv);
568 rv = DoResolveProxy();
569 break;
570 case STATE_RESOLVE_PROXY_COMPLETE:
571 rv = DoResolveProxyComplete(rv);
572 break;
573 case STATE_WAIT_FOR_JOB:
574 DCHECK_EQ(OK, rv);
575 rv = DoWaitForJob();
576 break;
577 case STATE_WAIT_FOR_JOB_COMPLETE:
578 rv = DoWaitForJobComplete(rv);
579 break;
580 case STATE_INIT_CONNECTION:
581 DCHECK_EQ(OK, rv);
582 rv = DoInitConnection();
583 break;
584 case STATE_INIT_CONNECTION_COMPLETE:
585 rv = DoInitConnectionComplete(rv);
586 break;
587 case STATE_WAITING_USER_ACTION:
588 rv = DoWaitingUserAction(rv);
589 break;
590 case STATE_RESTART_TUNNEL_AUTH:
591 DCHECK_EQ(OK, rv);
592 rv = DoRestartTunnelAuth();
593 break;
594 case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
595 rv = DoRestartTunnelAuthComplete(rv);
596 break;
597 case STATE_CREATE_STREAM:
598 DCHECK_EQ(OK, rv);
599 rv = DoCreateStream();
600 break;
601 case STATE_CREATE_STREAM_COMPLETE:
602 rv = DoCreateStreamComplete(rv);
603 break;
604 default:
605 NOTREACHED() << "bad state";
606 rv = ERR_FAILED;
607 break;
609 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
610 return rv;
613 int HttpStreamFactoryImpl::Job::StartInternal() {
614 CHECK_EQ(STATE_NONE, next_state_);
615 next_state_ = STATE_START;
616 int rv = RunLoop(OK);
617 DCHECK_EQ(ERR_IO_PENDING, rv);
618 return rv;
621 int HttpStreamFactoryImpl::Job::DoStart() {
622 if (IsAlternate()) {
623 server_ = alternative_service_.host_port_pair();
624 } else {
625 server_ = HostPortPair::FromURL(request_info_.url);
627 origin_url_ =
628 stream_factory_->ApplyHostMappingRules(request_info_.url, &server_);
630 net_log_.BeginEvent(
631 NetLog::TYPE_HTTP_STREAM_JOB,
632 base::Bind(&NetLogHttpStreamJobCallback, &request_info_.url, &origin_url_,
633 &alternative_service_, priority_));
635 // Don't connect to restricted ports.
636 bool is_port_allowed = IsPortAllowedByDefault(server_.port());
637 if (request_info_.url.SchemeIs("ftp")) {
638 // Never share connection with other jobs for FTP requests.
639 DCHECK(!waiting_job_);
641 is_port_allowed = IsPortAllowedByFtp(server_.port());
643 if (!is_port_allowed && !IsPortAllowedByOverride(server_.port())) {
644 if (waiting_job_) {
645 waiting_job_->Resume(this);
646 waiting_job_ = NULL;
648 return ERR_UNSAFE_PORT;
651 next_state_ = STATE_RESOLVE_PROXY;
652 return OK;
655 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
656 DCHECK(!pac_request_);
657 DCHECK(session_);
659 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
661 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
662 proxy_info_.UseDirect();
663 return OK;
666 // TODO(rch): remove this code since Alt-Svc seems to prohibit it.
667 GURL url_for_proxy = origin_url_;
668 // For SPDY via Alt-Svc, set |alternative_service_url_| to
669 // https://<alternative host>:<alternative port>/...
670 // so the proxy resolution works with the actual destination, and so
671 // that the correct socket pool is used.
672 if (IsSpdyAlternate()) {
673 // TODO(rch): Figure out how to make QUIC iteract with PAC
674 // scripts. By not re-writing the URL, we will query the PAC script
675 // for the proxy to use to reach the original URL via TCP. But
676 // the alternate request will be going via UDP to a different port.
677 GURL::Replacements replacements;
678 // new_port needs to be in scope here because GURL::Replacements references
679 // the memory contained by it directly.
680 const std::string new_port = base::IntToString(alternative_service_.port);
681 replacements.SetSchemeStr("https");
682 replacements.SetPortStr(new_port);
683 url_for_proxy = url_for_proxy.ReplaceComponents(replacements);
686 return session_->proxy_service()->ResolveProxy(
687 url_for_proxy, request_info_.load_flags, &proxy_info_, io_callback_,
688 &pac_request_, session_->network_delegate(), net_log_);
691 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
692 pac_request_ = NULL;
694 if (result == OK) {
695 // Remove unsupported proxies from the list.
696 int supported_proxies =
697 ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_HTTP |
698 ProxyServer::SCHEME_HTTPS | ProxyServer::SCHEME_SOCKS4 |
699 ProxyServer::SCHEME_SOCKS5;
701 if (session_->params().enable_quic_for_proxies)
702 supported_proxies |= ProxyServer::SCHEME_QUIC;
704 proxy_info_.RemoveProxiesWithoutScheme(supported_proxies);
706 if (proxy_info_.is_empty()) {
707 // No proxies/direct to choose from. This happens when we don't support
708 // any of the proxies in the returned list.
709 result = ERR_NO_SUPPORTED_PROXIES;
710 } else if (using_quic_ &&
711 (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
712 // QUIC can not be spoken to non-QUIC proxies. This error should not be
713 // user visible, because the non-alternate job should be resumed.
714 result = ERR_NO_SUPPORTED_PROXIES;
718 if (result != OK) {
719 if (waiting_job_) {
720 waiting_job_->Resume(this);
721 waiting_job_ = NULL;
723 return result;
726 if (blocking_job_)
727 next_state_ = STATE_WAIT_FOR_JOB;
728 else
729 next_state_ = STATE_INIT_CONNECTION;
730 return OK;
733 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
734 return session_->params().enable_quic &&
735 session_->params().origin_to_force_quic_on.Equals(server_) &&
736 proxy_info_.is_direct();
739 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
740 DCHECK(blocking_job_);
741 next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
742 return ERR_IO_PENDING;
745 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
746 DCHECK(!blocking_job_);
747 DCHECK_EQ(OK, result);
748 next_state_ = STATE_INIT_CONNECTION;
749 return OK;
752 int HttpStreamFactoryImpl::Job::DoInitConnection() {
753 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462812 is fixed.
754 tracked_objects::ScopedTracker tracking_profile(
755 FROM_HERE_WITH_EXPLICIT_FUNCTION(
756 "462812 HttpStreamFactoryImpl::Job::DoInitConnection"));
757 DCHECK(!blocking_job_);
758 DCHECK(!connection_->is_initialized());
759 DCHECK(proxy_info_.proxy_server().is_valid());
760 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
762 using_ssl_ = origin_url_.SchemeIs("https") || origin_url_.SchemeIs("wss") ||
763 IsSpdyAlternate();
764 using_spdy_ = false;
766 if (ShouldForceQuic())
767 using_quic_ = true;
769 DCHECK(!using_quic_ || session_->params().enable_quic);
771 if (proxy_info_.is_quic()) {
772 using_quic_ = true;
773 DCHECK(session_->params().enable_quic_for_proxies);
776 if (using_quic_) {
777 if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
778 NOTREACHED();
779 // TODO(rch): support QUIC proxies for HTTPS urls.
780 return ERR_NOT_IMPLEMENTED;
782 HostPortPair destination = proxy_info_.is_quic()
783 ? proxy_info_.proxy_server().host_port_pair()
784 : server_;
785 next_state_ = STATE_INIT_CONNECTION_COMPLETE;
786 bool secure_quic = using_ssl_ || proxy_info_.is_quic();
787 int rv = quic_request_.Request(
788 destination, secure_quic, request_info_.privacy_mode,
789 request_info_.method, net_log_, io_callback_);
790 if (rv == OK) {
791 using_existing_quic_session_ = true;
792 } else {
793 // OK, there's no available QUIC session. Let |waiting_job_| resume
794 // if it's paused.
795 if (waiting_job_) {
796 waiting_job_->Resume(this);
797 waiting_job_ = NULL;
800 return rv;
803 SpdySessionKey spdy_session_key = GetSpdySessionKey();
805 // Check first if we have a spdy session for this group. If so, then go
806 // straight to using that.
807 if (CanUseExistingSpdySession()) {
808 base::WeakPtr<SpdySession> spdy_session =
809 session_->spdy_session_pool()->FindAvailableSession(spdy_session_key,
810 net_log_);
811 if (spdy_session) {
812 // If we're preconnecting, but we already have a SpdySession, we don't
813 // actually need to preconnect any sockets, so we're done.
814 if (IsPreconnecting())
815 return OK;
816 using_spdy_ = true;
817 next_state_ = STATE_CREATE_STREAM;
818 existing_spdy_session_ = spdy_session;
819 return OK;
822 if (request_ && !request_->HasSpdySessionKey() && using_ssl_) {
823 // Update the spdy session key for the request that launched this job.
824 request_->SetSpdySessionKey(spdy_session_key);
827 // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
828 // paused.
829 if (waiting_job_) {
830 waiting_job_->Resume(this);
831 waiting_job_ = NULL;
834 if (proxy_info_.is_http() || proxy_info_.is_https())
835 establishing_tunnel_ = using_ssl_;
837 // TODO(bnc): s/want_spdy_over_npn/expect_spdy_over_npn/
838 bool want_spdy_over_npn = IsAlternate();
840 if (proxy_info_.is_https()) {
841 InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
842 &proxy_ssl_config_,
843 true /* is a proxy server */);
844 // Disable revocation checking for HTTPS proxies since the revocation
845 // requests are probably going to need to go through the proxy too.
846 proxy_ssl_config_.rev_checking_enabled = false;
848 if (using_ssl_) {
849 InitSSLConfig(server_, &server_ssl_config_, false /* not a proxy server */);
852 base::WeakPtr<HttpServerProperties> http_server_properties =
853 session_->http_server_properties();
854 if (http_server_properties) {
855 http_server_properties->MaybeForceHTTP11(server_, &server_ssl_config_);
856 if (proxy_info_.is_http() || proxy_info_.is_https()) {
857 http_server_properties->MaybeForceHTTP11(
858 proxy_info_.proxy_server().host_port_pair(), &proxy_ssl_config_);
862 if (IsPreconnecting()) {
863 DCHECK(!stream_factory_->for_websockets_);
864 return PreconnectSocketsForHttpRequest(
865 GetSocketGroup(), server_, request_info_.extra_headers,
866 request_info_.load_flags, priority_, session_, proxy_info_,
867 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
868 request_info_.privacy_mode, net_log_, num_streams_);
871 // If we can't use a SPDY session, don't bother checking for one after
872 // the hostname is resolved.
873 OnHostResolutionCallback resolution_callback =
874 CanUseExistingSpdySession()
875 ? base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
876 spdy_session_key)
877 : OnHostResolutionCallback();
878 if (stream_factory_->for_websockets_) {
879 // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
880 SSLConfig websocket_server_ssl_config = server_ssl_config_;
881 websocket_server_ssl_config.next_protos.clear();
882 return InitSocketHandleForWebSocketRequest(
883 GetSocketGroup(), server_, request_info_.extra_headers,
884 request_info_.load_flags, priority_, session_, proxy_info_,
885 want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
886 request_info_.privacy_mode, net_log_, connection_.get(),
887 resolution_callback, io_callback_);
890 return InitSocketHandleForHttpRequest(
891 GetSocketGroup(), server_, request_info_.extra_headers,
892 request_info_.load_flags, priority_, session_, proxy_info_,
893 want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
894 request_info_.privacy_mode, net_log_, connection_.get(),
895 resolution_callback, io_callback_);
898 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
899 if (IsPreconnecting()) {
900 if (using_quic_)
901 return result;
902 DCHECK_EQ(OK, result);
903 return OK;
906 if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
907 // We found a SPDY connection after resolving the host. This is
908 // probably an IP pooled connection.
909 SpdySessionKey spdy_session_key = GetSpdySessionKey();
910 existing_spdy_session_ =
911 session_->spdy_session_pool()->FindAvailableSession(
912 spdy_session_key, net_log_);
913 if (existing_spdy_session_) {
914 using_spdy_ = true;
915 next_state_ = STATE_CREATE_STREAM;
916 } else {
917 // It is possible that the spdy session no longer exists.
918 ReturnToStateInitConnection(true /* close connection */);
920 return OK;
923 if (proxy_info_.is_quic() && using_quic_ &&
924 (result == ERR_QUIC_PROTOCOL_ERROR ||
925 result == ERR_QUIC_HANDSHAKE_FAILED)) {
926 using_quic_ = false;
927 return ReconsiderProxyAfterError(result);
930 // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
931 // errors, such as ignoring certificate errors for Alternate-Protocol.
932 if (result < 0 && waiting_job_) {
933 waiting_job_->Resume(this);
934 waiting_job_ = NULL;
937 // |result| may be the result of any of the stacked pools. The following
938 // logic is used when determining how to interpret an error.
939 // If |result| < 0:
940 // and connection_->socket() != NULL, then the SSL handshake ran and it
941 // is a potentially recoverable error.
942 // and connection_->socket == NULL and connection_->is_ssl_error() is true,
943 // then the SSL handshake ran with an unrecoverable error.
944 // otherwise, the error came from one of the other pools.
945 bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
946 connection_->is_ssl_error());
948 if (ssl_started && (result == OK || IsCertificateError(result))) {
949 if (using_quic_ && result == OK) {
950 was_npn_negotiated_ = true;
951 NextProto protocol_negotiated =
952 SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
953 protocol_negotiated_ = protocol_negotiated;
954 } else {
955 SSLClientSocket* ssl_socket =
956 static_cast<SSLClientSocket*>(connection_->socket());
957 if (ssl_socket->WasNpnNegotiated()) {
958 was_npn_negotiated_ = true;
959 std::string proto;
960 SSLClientSocket::NextProtoStatus status =
961 ssl_socket->GetNextProto(&proto);
962 NextProto protocol_negotiated =
963 SSLClientSocket::NextProtoFromString(proto);
964 protocol_negotiated_ = protocol_negotiated;
965 net_log_.AddEvent(
966 NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
967 base::Bind(&NetLogHttpStreamProtoCallback,
968 status, &proto));
969 if (ssl_socket->was_spdy_negotiated())
970 SwitchToSpdyMode();
973 } else if (proxy_info_.is_https() && connection_->socket() &&
974 result == OK) {
975 ProxyClientSocket* proxy_socket =
976 static_cast<ProxyClientSocket*>(connection_->socket());
977 if (proxy_socket->IsUsingSpdy()) {
978 was_npn_negotiated_ = true;
979 protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
980 SwitchToSpdyMode();
984 if (result == ERR_PROXY_AUTH_REQUESTED ||
985 result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
986 DCHECK(!ssl_started);
987 // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
988 // SSL socket, but there was an error before that could happen. This
989 // puts the in progress HttpProxy socket into |connection_| in order to
990 // complete the auth (or read the response body). The tunnel restart code
991 // is careful to remove it before returning control to the rest of this
992 // class.
993 connection_.reset(connection_->release_pending_http_proxy_connection());
994 return result;
997 if (!ssl_started && result < 0 && IsAlternate()) {
998 job_status_ = STATUS_BROKEN;
999 MaybeMarkAlternativeServiceBroken();
1000 return result;
1003 if (using_quic_) {
1004 if (result < 0) {
1005 job_status_ = STATUS_BROKEN;
1006 MaybeMarkAlternativeServiceBroken();
1007 return result;
1009 stream_ = quic_request_.ReleaseStream();
1010 next_state_ = STATE_NONE;
1011 return OK;
1014 if (result < 0 && !ssl_started)
1015 return ReconsiderProxyAfterError(result);
1016 establishing_tunnel_ = false;
1018 if (connection_->socket()) {
1019 // We officially have a new connection. Record the type.
1020 if (!connection_->is_reused()) {
1021 ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
1022 UpdateConnectionTypeHistograms(type);
1026 // Handle SSL errors below.
1027 if (using_ssl_) {
1028 DCHECK(ssl_started);
1029 if (IsCertificateError(result)) {
1030 if (using_spdy_ && IsAlternate() && origin_url_.SchemeIs("http")) {
1031 // We ignore certificate errors for http over spdy.
1032 spdy_certificate_error_ = result;
1033 result = OK;
1034 } else {
1035 result = HandleCertificateError(result);
1036 if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1037 ReturnToStateInitConnection(true /* close connection */);
1038 return result;
1042 if (result < 0)
1043 return result;
1046 next_state_ = STATE_CREATE_STREAM;
1047 return OK;
1050 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1051 // This state indicates that the stream request is in a partially
1052 // completed state, and we've called back to the delegate for more
1053 // information.
1055 // We're always waiting here for the delegate to call us back.
1056 return ERR_IO_PENDING;
1059 int HttpStreamFactoryImpl::Job::SetSpdyHttpStream(
1060 base::WeakPtr<SpdySession> session, bool direct) {
1061 // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1062 // implemented.
1063 if (stream_factory_->for_websockets_)
1064 return ERR_NOT_IMPLEMENTED;
1066 // TODO(willchan): Delete this code, because eventually, the
1067 // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1068 // will know when SpdySessions become available.
1070 bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1071 stream_.reset(new SpdyHttpStream(session, use_relative_url));
1072 return OK;
1075 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1076 // TODO(pkasting): Remove ScopedTracker below once crbug.com/462811 is fixed.
1077 tracked_objects::ScopedTracker tracking_profile(
1078 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1079 "462811 HttpStreamFactoryImpl::Job::DoCreateStream"));
1080 DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1082 next_state_ = STATE_CREATE_STREAM_COMPLETE;
1084 // We only set the socket motivation if we're the first to use
1085 // this socket. Is there a race for two SPDY requests? We really
1086 // need to plumb this through to the connect level.
1087 if (connection_->socket() && !connection_->is_reused())
1088 SetSocketMotivation();
1090 if (!using_spdy_) {
1091 // We may get ftp scheme when fetching ftp resources through proxy.
1092 bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1093 (request_info_.url.SchemeIs("http") ||
1094 request_info_.url.SchemeIs("ftp"));
1095 if (stream_factory_->for_websockets_) {
1096 DCHECK(request_);
1097 DCHECK(request_->websocket_handshake_stream_create_helper());
1098 websocket_stream_.reset(
1099 request_->websocket_handshake_stream_create_helper()
1100 ->CreateBasicStream(connection_.Pass(), using_proxy));
1101 } else {
1102 stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1104 return OK;
1107 CHECK(!stream_.get());
1109 bool direct = !IsHttpsProxyAndHttpUrl();
1110 if (existing_spdy_session_.get()) {
1111 // We picked up an existing session, so we don't need our socket.
1112 if (connection_->socket())
1113 connection_->socket()->Disconnect();
1114 connection_->Reset();
1116 int set_result = SetSpdyHttpStream(existing_spdy_session_, direct);
1117 existing_spdy_session_.reset();
1118 return set_result;
1121 SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1122 SpdySessionKey spdy_session_key = GetSpdySessionKey();
1123 base::WeakPtr<SpdySession> spdy_session =
1124 spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1126 if (spdy_session) {
1127 return SetSpdyHttpStream(spdy_session, direct);
1130 spdy_session =
1131 spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1132 connection_.Pass(),
1133 net_log_,
1134 spdy_certificate_error_,
1135 using_ssl_);
1136 if (!spdy_session->HasAcceptableTransportSecurity()) {
1137 spdy_session->CloseSessionOnError(
1138 ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1139 return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1142 new_spdy_session_ = spdy_session;
1143 spdy_session_direct_ = direct;
1144 const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1145 base::WeakPtr<HttpServerProperties> http_server_properties =
1146 session_->http_server_properties();
1147 if (http_server_properties)
1148 http_server_properties->SetSupportsSpdy(host_port_pair, true);
1150 // Create a SpdyHttpStream attached to the session;
1151 // OnNewSpdySessionReadyCallback is not called until an event loop
1152 // iteration later, so if the SpdySession is closed between then, allow
1153 // reuse state from the underlying socket, sampled by SpdyHttpStream,
1154 // bubble up to the request.
1155 return SetSpdyHttpStream(new_spdy_session_, spdy_session_direct_);
1158 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1159 if (result < 0)
1160 return result;
1162 session_->proxy_service()->ReportSuccess(proxy_info_,
1163 session_->network_delegate());
1164 next_state_ = STATE_NONE;
1165 return OK;
1168 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1169 next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1170 ProxyClientSocket* proxy_socket =
1171 static_cast<ProxyClientSocket*>(connection_->socket());
1172 return proxy_socket->RestartWithAuth(io_callback_);
1175 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1176 if (result == ERR_PROXY_AUTH_REQUESTED)
1177 return result;
1179 if (result == OK) {
1180 // Now that we've got the HttpProxyClientSocket connected. We have
1181 // to release it as an idle socket into the pool and start the connection
1182 // process from the beginning. Trying to pass it in with the
1183 // SSLSocketParams might cause a deadlock since params are dispatched
1184 // interchangeably. This request won't necessarily get this http proxy
1185 // socket, but there will be forward progress.
1186 establishing_tunnel_ = false;
1187 ReturnToStateInitConnection(false /* do not close connection */);
1188 return OK;
1191 return ReconsiderProxyAfterError(result);
1194 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1195 bool close_connection) {
1196 if (close_connection && connection_->socket())
1197 connection_->socket()->Disconnect();
1198 connection_->Reset();
1200 if (request_)
1201 request_->RemoveRequestFromSpdySessionRequestMap();
1203 next_state_ = STATE_INIT_CONNECTION;
1206 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1207 if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1208 connection_->socket()->SetSubresourceSpeculation();
1209 else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1210 connection_->socket()->SetOmniboxSpeculation();
1211 // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1214 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1215 if (!proxy_info_.is_https())
1216 return false;
1217 if (IsAlternate()) {
1218 // We currently only support Alternate-Protocol where the original scheme
1219 // is http.
1220 DCHECK(origin_url_.SchemeIs("http"));
1221 return origin_url_.SchemeIs("http");
1223 return request_info_.url.SchemeIs("http");
1226 bool HttpStreamFactoryImpl::Job::IsAlternate() const {
1227 return alternative_service_.protocol != UNINITIALIZED_ALTERNATE_PROTOCOL;
1230 bool HttpStreamFactoryImpl::Job::IsSpdyAlternate() const {
1231 return alternative_service_.protocol >= NPN_SPDY_MINIMUM_VERSION &&
1232 alternative_service_.protocol <= NPN_SPDY_MAXIMUM_VERSION;
1235 void HttpStreamFactoryImpl::Job::InitSSLConfig(const HostPortPair& server,
1236 SSLConfig* ssl_config,
1237 bool is_proxy) const {
1238 if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1239 // When connecting through an HTTPS proxy, disable TLS False Start so
1240 // that client authentication errors can be distinguished between those
1241 // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1242 // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1243 // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1244 // TODO(rch): This assumes that the HTTPS proxy will only request a
1245 // client certificate during the initial handshake.
1246 // http://crbug.com/59292
1247 ssl_config->false_start_enabled = false;
1250 enum {
1251 FALLBACK_NONE = 0, // SSL version fallback did not occur.
1252 FALLBACK_SSL3 = 1, // Fell back to SSL 3.0.
1253 FALLBACK_TLS1 = 2, // Fell back to TLS 1.0.
1254 FALLBACK_TLS1_1 = 3, // Fell back to TLS 1.1.
1255 FALLBACK_MAX
1258 int fallback = FALLBACK_NONE;
1259 if (ssl_config->version_fallback) {
1260 switch (ssl_config->version_max) {
1261 case SSL_PROTOCOL_VERSION_SSL3:
1262 fallback = FALLBACK_SSL3;
1263 break;
1264 case SSL_PROTOCOL_VERSION_TLS1:
1265 fallback = FALLBACK_TLS1;
1266 break;
1267 case SSL_PROTOCOL_VERSION_TLS1_1:
1268 fallback = FALLBACK_TLS1_1;
1269 break;
1272 UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1273 fallback, FALLBACK_MAX);
1275 UMA_HISTOGRAM_BOOLEAN("Net.ConnectionUsedSSLDeprecatedCipherFallback",
1276 ssl_config->enable_deprecated_cipher_suites);
1278 // We also wish to measure the amount of fallback connections for a host that
1279 // we know implements TLS up to 1.2. Ideally there would be no fallback here
1280 // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1281 // caused by network middleware rather than buggy HTTPS servers.
1282 const std::string& host = server.host();
1283 if (!is_proxy &&
1284 host.size() >= 10 &&
1285 host.compare(host.size() - 10, 10, "google.com") == 0 &&
1286 (host.size() == 10 || host[host.size()-11] == '.')) {
1287 UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1288 fallback, FALLBACK_MAX);
1291 if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1292 ssl_config->verify_ev_cert = true;
1294 // Disable Channel ID if privacy mode is enabled.
1295 if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1296 ssl_config->channel_id_enabled = false;
1300 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1301 DCHECK(!pac_request_);
1302 DCHECK(session_);
1304 // A failure to resolve the hostname or any error related to establishing a
1305 // TCP connection could be grounds for trying a new proxy configuration.
1307 // Why do this when a hostname cannot be resolved? Some URLs only make sense
1308 // to proxy servers. The hostname in those URLs might fail to resolve if we
1309 // are still using a non-proxy config. We need to check if a proxy config
1310 // now exists that corresponds to a proxy server that could load the URL.
1312 switch (error) {
1313 case ERR_PROXY_CONNECTION_FAILED:
1314 case ERR_NAME_NOT_RESOLVED:
1315 case ERR_INTERNET_DISCONNECTED:
1316 case ERR_ADDRESS_UNREACHABLE:
1317 case ERR_CONNECTION_CLOSED:
1318 case ERR_CONNECTION_TIMED_OUT:
1319 case ERR_CONNECTION_RESET:
1320 case ERR_CONNECTION_REFUSED:
1321 case ERR_CONNECTION_ABORTED:
1322 case ERR_TIMED_OUT:
1323 case ERR_TUNNEL_CONNECTION_FAILED:
1324 case ERR_SOCKS_CONNECTION_FAILED:
1325 // This can happen in the case of trying to talk to a proxy using SSL, and
1326 // ending up talking to a captive portal that supports SSL instead.
1327 case ERR_PROXY_CERTIFICATE_INVALID:
1328 // This can happen when trying to talk SSL to a non-SSL server (Like a
1329 // captive portal).
1330 case ERR_QUIC_PROTOCOL_ERROR:
1331 case ERR_QUIC_HANDSHAKE_FAILED:
1332 case ERR_SSL_PROTOCOL_ERROR:
1333 break;
1334 case ERR_SOCKS_CONNECTION_HOST_UNREACHABLE:
1335 // Remap the SOCKS-specific "host unreachable" error to a more
1336 // generic error code (this way consumers like the link doctor
1337 // know to substitute their error page).
1339 // Note that if the host resolving was done by the SOCKS5 proxy, we can't
1340 // differentiate between a proxy-side "host not found" versus a proxy-side
1341 // "address unreachable" error, and will report both of these failures as
1342 // ERR_ADDRESS_UNREACHABLE.
1343 return ERR_ADDRESS_UNREACHABLE;
1344 default:
1345 return error;
1348 if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1349 return error;
1352 if (proxy_info_.is_https() && proxy_ssl_config_.send_client_cert) {
1353 session_->ssl_client_auth_cache()->Remove(
1354 proxy_info_.proxy_server().host_port_pair());
1357 int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1358 request_info_.url, request_info_.load_flags, error, &proxy_info_,
1359 io_callback_, &pac_request_, session_->network_delegate(), net_log_);
1360 if (rv == OK || rv == ERR_IO_PENDING) {
1361 // If the error was during connection setup, there is no socket to
1362 // disconnect.
1363 if (connection_->socket())
1364 connection_->socket()->Disconnect();
1365 connection_->Reset();
1366 if (request_)
1367 request_->RemoveRequestFromSpdySessionRequestMap();
1368 next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
1369 } else {
1370 // If ReconsiderProxyAfterError() failed synchronously, it means
1371 // there was nothing left to fall-back to, so fail the transaction
1372 // with the last connection error we got.
1373 // TODO(eroman): This is a confusing contract, make it more obvious.
1374 rv = error;
1377 return rv;
1380 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1381 DCHECK(using_ssl_);
1382 DCHECK(IsCertificateError(error));
1384 SSLClientSocket* ssl_socket =
1385 static_cast<SSLClientSocket*>(connection_->socket());
1386 ssl_socket->GetSSLInfo(&ssl_info_);
1388 // Add the bad certificate to the set of allowed certificates in the
1389 // SSL config object. This data structure will be consulted after calling
1390 // RestartIgnoringLastError(). And the user will be asked interactively
1391 // before RestartIgnoringLastError() is ever called.
1392 SSLConfig::CertAndStatus bad_cert;
1394 // |ssl_info_.cert| may be NULL if we failed to create
1395 // X509Certificate for whatever reason, but normally it shouldn't
1396 // happen, unless this code is used inside sandbox.
1397 if (ssl_info_.cert.get() == NULL ||
1398 !X509Certificate::GetDEREncoded(ssl_info_.cert->os_cert_handle(),
1399 &bad_cert.der_cert)) {
1400 return error;
1402 bad_cert.cert_status = ssl_info_.cert_status;
1403 server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1405 int load_flags = request_info_.load_flags;
1406 if (session_->params().ignore_certificate_errors)
1407 load_flags |= LOAD_IGNORE_ALL_CERT_ERRORS;
1408 if (ssl_socket->IgnoreCertError(error, load_flags))
1409 return OK;
1410 return error;
1413 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1414 if (HttpStreamFactory::spdy_enabled())
1415 using_spdy_ = true;
1418 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1419 DCHECK_GE(num_streams_, 0);
1420 return num_streams_ > 0;
1423 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1424 return !IsPreconnecting() && !request_;
1427 void HttpStreamFactoryImpl::Job::ReportJobSucceededForRequest() {
1428 if (using_existing_quic_session_) {
1429 // If an existing session was used, then no TCP connection was
1430 // started.
1431 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE);
1432 } else if (IsAlternate()) {
1433 // This job was the alternate protocol job, and hence won the race.
1434 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE);
1435 } else {
1436 // This job was the normal job, and hence the alternate protocol job lost
1437 // the race.
1438 HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE);
1442 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1443 DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1444 other_job_status_ = job.job_status_;
1445 other_job_alternative_service_ = job.alternative_service_;
1446 MaybeMarkAlternativeServiceBroken();
1449 void HttpStreamFactoryImpl::Job::MaybeMarkAlternativeServiceBroken() {
1450 if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1451 return;
1453 if (IsAlternate()) {
1454 if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1455 HistogramBrokenAlternateProtocolLocation(
1456 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1457 session_->http_server_properties()->MarkAlternativeServiceBroken(
1458 alternative_service_);
1460 return;
1463 if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1464 HistogramBrokenAlternateProtocolLocation(
1465 BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1466 session_->http_server_properties()->MarkAlternativeServiceBroken(
1467 other_job_alternative_service_);
1471 ClientSocketPoolManager::SocketGroupType
1472 HttpStreamFactoryImpl::Job::GetSocketGroup() const {
1473 std::string scheme = origin_url_.scheme();
1474 if (scheme == "https" || scheme == "wss" || IsSpdyAlternate())
1475 return ClientSocketPoolManager::SSL_GROUP;
1477 if (scheme == "ftp")
1478 return ClientSocketPoolManager::FTP_GROUP;
1480 return ClientSocketPoolManager::NORMAL_GROUP;
1483 } // namespace net