Upstream version 9.37.195.0
[platform/framework/web/crosswalk.git] / src / net / http / http_stream_factory_impl_job.cc
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.
4
5 #include "net/http/http_stream_factory_impl_job.h"
6
7 #include <algorithm>
8 #include <string>
9
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"
40
41 namespace net {
42
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;
53 }
54
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     const std::string* server_protos,
61     NetLog::LogLevel /* log_level */) {
62   base::DictionaryValue* dict = new base::DictionaryValue();
63
64   dict->SetString("next_proto_status",
65                   SSLClientSocket::NextProtoStatusToString(status));
66   dict->SetString("proto", *proto);
67   dict->SetString("server_protos",
68                   SSLClientSocket::ServerProtosToString(*server_protos));
69   return dict;
70 }
71
72 HttpStreamFactoryImpl::Job::Job(HttpStreamFactoryImpl* stream_factory,
73                                 HttpNetworkSession* session,
74                                 const HttpRequestInfo& request_info,
75                                 RequestPriority priority,
76                                 const SSLConfig& server_ssl_config,
77                                 const SSLConfig& proxy_ssl_config,
78                                 NetLog* net_log)
79     : request_(NULL),
80       request_info_(request_info),
81       priority_(priority),
82       server_ssl_config_(server_ssl_config),
83       proxy_ssl_config_(proxy_ssl_config),
84       net_log_(BoundNetLog::Make(net_log, NetLog::SOURCE_HTTP_STREAM_JOB)),
85       io_callback_(base::Bind(&Job::OnIOComplete, base::Unretained(this))),
86       connection_(new ClientSocketHandle),
87       session_(session),
88       stream_factory_(stream_factory),
89       next_state_(STATE_NONE),
90       pac_request_(NULL),
91       blocking_job_(NULL),
92       waiting_job_(NULL),
93       using_ssl_(false),
94       using_spdy_(false),
95       using_quic_(false),
96       quic_request_(session_->quic_stream_factory()),
97       using_existing_quic_session_(false),
98       spdy_certificate_error_(OK),
99       establishing_tunnel_(false),
100       was_npn_negotiated_(false),
101       protocol_negotiated_(kProtoUnknown),
102       num_streams_(0),
103       spdy_session_direct_(false),
104       job_status_(STATUS_RUNNING),
105       other_job_status_(STATUS_RUNNING),
106       ptr_factory_(this) {
107   DCHECK(stream_factory);
108   DCHECK(session);
109 }
110
111 HttpStreamFactoryImpl::Job::~Job() {
112   net_log_.EndEvent(NetLog::TYPE_HTTP_STREAM_JOB);
113
114   // When we're in a partially constructed state, waiting for the user to
115   // provide certificate handling information or authentication, we can't reuse
116   // this stream at all.
117   if (next_state_ == STATE_WAITING_USER_ACTION) {
118     connection_->socket()->Disconnect();
119     connection_.reset();
120   }
121
122   if (pac_request_)
123     session_->proxy_service()->CancelPacRequest(pac_request_);
124
125   // The stream could be in a partial state.  It is not reusable.
126   if (stream_.get() && next_state_ != STATE_DONE)
127     stream_->Close(true /* not reusable */);
128 }
129
130 void HttpStreamFactoryImpl::Job::Start(Request* request) {
131   DCHECK(request);
132   request_ = request;
133   StartInternal();
134 }
135
136 int HttpStreamFactoryImpl::Job::Preconnect(int num_streams) {
137   DCHECK_GT(num_streams, 0);
138   HostPortPair origin_server =
139       HostPortPair(request_info_.url.HostNoBrackets(),
140                    request_info_.url.EffectiveIntPort());
141   base::WeakPtr<HttpServerProperties> http_server_properties =
142       session_->http_server_properties();
143   if (http_server_properties &&
144       http_server_properties->SupportsSpdy(origin_server)) {
145     num_streams_ = 1;
146   } else {
147     num_streams_ = num_streams;
148   }
149   return StartInternal();
150 }
151
152 int HttpStreamFactoryImpl::Job::RestartTunnelWithProxyAuth(
153     const AuthCredentials& credentials) {
154   DCHECK(establishing_tunnel_);
155   next_state_ = STATE_RESTART_TUNNEL_AUTH;
156   stream_.reset();
157   return RunLoop(OK);
158 }
159
160 LoadState HttpStreamFactoryImpl::Job::GetLoadState() const {
161   switch (next_state_) {
162     case STATE_RESOLVE_PROXY_COMPLETE:
163       return session_->proxy_service()->GetLoadState(pac_request_);
164     case STATE_INIT_CONNECTION_COMPLETE:
165     case STATE_CREATE_STREAM_COMPLETE:
166       return using_quic_ ? LOAD_STATE_CONNECTING : connection_->GetLoadState();
167     default:
168       return LOAD_STATE_IDLE;
169   }
170 }
171
172 void HttpStreamFactoryImpl::Job::MarkAsAlternate(
173     const GURL& original_url,
174     PortAlternateProtocolPair alternate) {
175   DCHECK(!original_url_.get());
176   original_url_.reset(new GURL(original_url));
177   if (alternate.protocol == QUIC) {
178     DCHECK(session_->params().enable_quic);
179     using_quic_ = true;
180   }
181 }
182
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;
190 }
191
192 void HttpStreamFactoryImpl::Job::Resume(Job* job) {
193   DCHECK_EQ(blocking_job_, job);
194   blocking_job_ = NULL;
195
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));
203   }
204 }
205
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();
218     }
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();
226     }
227     stream_factory_->OnOrphanedJobComplete(this);
228   }
229 }
230
231 void HttpStreamFactoryImpl::Job::SetPriority(RequestPriority priority) {
232   priority_ = priority;
233   // TODO(akalin): Propagate this to |connection_| and maybe the
234   // preconnect state.
235 }
236
237 bool HttpStreamFactoryImpl::Job::was_npn_negotiated() const {
238   return was_npn_negotiated_;
239 }
240
241 NextProto HttpStreamFactoryImpl::Job::protocol_negotiated() const {
242   return protocol_negotiated_;
243 }
244
245 bool HttpStreamFactoryImpl::Job::using_spdy() const {
246   return using_spdy_;
247 }
248
249 const SSLConfig& HttpStreamFactoryImpl::Job::server_ssl_config() const {
250   return server_ssl_config_;
251 }
252
253 const SSLConfig& HttpStreamFactoryImpl::Job::proxy_ssl_config() const {
254   return proxy_ssl_config_;
255 }
256
257 const ProxyInfo& HttpStreamFactoryImpl::Job::proxy_info() const {
258   return proxy_info_;
259 }
260
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_);
268 }
269
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   PrivacyMode privacy_mode = request_info_.privacy_mode;
275   if (IsHttpsProxyAndHttpUrl()) {
276     return SpdySessionKey(proxy_info_.proxy_server().host_port_pair(),
277                           ProxyServer::Direct(),
278                           privacy_mode);
279   } else {
280     return SpdySessionKey(origin_,
281                           proxy_info_.proxy_server(),
282                           privacy_mode);
283   }
284 }
285
286 bool HttpStreamFactoryImpl::Job::CanUseExistingSpdySession() const {
287   // We need to make sure that if a spdy session was created for
288   // https://somehost/ that we don't use that session for http://somehost:443/.
289   // The only time we can use an existing session is if the request URL is
290   // https (the normal case) or if we're connection to a SPDY proxy, or
291   // if we're running with force_spdy_always_.  crbug.com/133176
292   // TODO(ricea): Add "wss" back to this list when SPDY WebSocket support is
293   // working.
294   return request_info_.url.SchemeIs("https") ||
295          proxy_info_.proxy_server().is_https() ||
296          session_->params().force_spdy_always;
297 }
298
299 void HttpStreamFactoryImpl::Job::OnStreamReadyCallback() {
300   DCHECK(stream_.get());
301   DCHECK(!IsPreconnecting());
302   DCHECK(!stream_factory_->for_websockets_);
303   if (IsOrphaned()) {
304     stream_factory_->OnOrphanedJobComplete(this);
305   } else {
306     request_->Complete(was_npn_negotiated(),
307                        protocol_negotiated(),
308                        using_spdy(),
309                        net_log_);
310     request_->OnStreamReady(this, server_ssl_config_, proxy_info_,
311                             stream_.release());
312   }
313   // |this| may be deleted after this call.
314 }
315
316 void HttpStreamFactoryImpl::Job::OnWebSocketHandshakeStreamReadyCallback() {
317   DCHECK(websocket_stream_);
318   DCHECK(!IsPreconnecting());
319   DCHECK(stream_factory_->for_websockets_);
320   // An orphaned WebSocket job will be closed immediately and
321   // never be ready.
322   DCHECK(!IsOrphaned());
323   request_->Complete(was_npn_negotiated(),
324                      protocol_negotiated(),
325                      using_spdy(),
326                      net_log_);
327   request_->OnWebSocketHandshakeStreamReady(this,
328                                             server_ssl_config_,
329                                             proxy_info_,
330                                             websocket_stream_.release());
331   // |this| may be deleted after this call.
332 }
333
334 void HttpStreamFactoryImpl::Job::OnNewSpdySessionReadyCallback() {
335   DCHECK(stream_.get());
336   DCHECK(!IsPreconnecting());
337   DCHECK(using_spdy());
338   // Note: an event loop iteration has passed, so |new_spdy_session_| may be
339   // NULL at this point if the SpdySession closed immediately after creation.
340   base::WeakPtr<SpdySession> spdy_session = new_spdy_session_;
341   new_spdy_session_.reset();
342
343   // TODO(jgraettinger): Notify the factory, and let that notify |request_|,
344   // rather than notifying |request_| directly.
345   if (IsOrphaned()) {
346     if (spdy_session) {
347       stream_factory_->OnNewSpdySessionReady(
348           spdy_session, spdy_session_direct_, server_ssl_config_, proxy_info_,
349           was_npn_negotiated(), protocol_negotiated(), using_spdy(), net_log_);
350     }
351     stream_factory_->OnOrphanedJobComplete(this);
352   } else {
353     request_->OnNewSpdySessionReady(
354         this, stream_.Pass(), spdy_session, spdy_session_direct_);
355   }
356   // |this| may be deleted after this call.
357 }
358
359 void HttpStreamFactoryImpl::Job::OnStreamFailedCallback(int result) {
360   DCHECK(!IsPreconnecting());
361   if (IsOrphaned())
362     stream_factory_->OnOrphanedJobComplete(this);
363   else
364     request_->OnStreamFailed(this, result, server_ssl_config_);
365   // |this| may be deleted after this call.
366 }
367
368 void HttpStreamFactoryImpl::Job::OnCertificateErrorCallback(
369     int result, const SSLInfo& ssl_info) {
370   DCHECK(!IsPreconnecting());
371   if (IsOrphaned())
372     stream_factory_->OnOrphanedJobComplete(this);
373   else
374     request_->OnCertificateError(this, result, server_ssl_config_, ssl_info);
375   // |this| may be deleted after this call.
376 }
377
378 void HttpStreamFactoryImpl::Job::OnNeedsProxyAuthCallback(
379     const HttpResponseInfo& response,
380     HttpAuthController* auth_controller) {
381   DCHECK(!IsPreconnecting());
382   if (IsOrphaned())
383     stream_factory_->OnOrphanedJobComplete(this);
384   else
385     request_->OnNeedsProxyAuth(
386         this, response, server_ssl_config_, proxy_info_, auth_controller);
387   // |this| may be deleted after this call.
388 }
389
390 void HttpStreamFactoryImpl::Job::OnNeedsClientAuthCallback(
391     SSLCertRequestInfo* cert_info) {
392   DCHECK(!IsPreconnecting());
393   if (IsOrphaned())
394     stream_factory_->OnOrphanedJobComplete(this);
395   else
396     request_->OnNeedsClientAuth(this, server_ssl_config_, cert_info);
397   // |this| may be deleted after this call.
398 }
399
400 void HttpStreamFactoryImpl::Job::OnHttpsProxyTunnelResponseCallback(
401     const HttpResponseInfo& response_info,
402     HttpStream* stream) {
403   DCHECK(!IsPreconnecting());
404   if (IsOrphaned())
405     stream_factory_->OnOrphanedJobComplete(this);
406   else
407     request_->OnHttpsProxyTunnelResponse(
408         this, response_info, server_ssl_config_, proxy_info_, stream);
409   // |this| may be deleted after this call.
410 }
411
412 void HttpStreamFactoryImpl::Job::OnPreconnectsComplete() {
413   DCHECK(!request_);
414   if (new_spdy_session_.get()) {
415     stream_factory_->OnNewSpdySessionReady(new_spdy_session_,
416                                            spdy_session_direct_,
417                                            server_ssl_config_,
418                                            proxy_info_,
419                                            was_npn_negotiated(),
420                                            protocol_negotiated(),
421                                            using_spdy(),
422                                            net_log_);
423   }
424   stream_factory_->OnPreconnectsComplete(this);
425   // |this| may be deleted after this call.
426 }
427
428 // static
429 int HttpStreamFactoryImpl::Job::OnHostResolution(
430     SpdySessionPool* spdy_session_pool,
431     const SpdySessionKey& spdy_session_key,
432     const AddressList& addresses,
433     const BoundNetLog& net_log) {
434   // It is OK to dereference spdy_session_pool, because the
435   // ClientSocketPoolManager will be destroyed in the same callback that
436   // destroys the SpdySessionPool.
437   return
438       spdy_session_pool->FindAvailableSession(spdy_session_key, net_log) ?
439       ERR_SPDY_SESSION_ALREADY_EXISTS : OK;
440 }
441
442 void HttpStreamFactoryImpl::Job::OnIOComplete(int result) {
443   RunLoop(result);
444 }
445
446 int HttpStreamFactoryImpl::Job::RunLoop(int result) {
447   result = DoLoop(result);
448
449   if (result == ERR_IO_PENDING)
450     return result;
451
452   // If there was an error, we should have already resumed the |waiting_job_|,
453   // if there was one.
454   DCHECK(result == OK || waiting_job_ == NULL);
455
456   if (IsPreconnecting()) {
457     base::MessageLoop::current()->PostTask(
458         FROM_HERE,
459         base::Bind(&HttpStreamFactoryImpl::Job::OnPreconnectsComplete,
460                    ptr_factory_.GetWeakPtr()));
461     return ERR_IO_PENDING;
462   }
463
464   if (IsCertificateError(result)) {
465     // Retrieve SSL information from the socket.
466     GetSSLInfo();
467
468     next_state_ = STATE_WAITING_USER_ACTION;
469     base::MessageLoop::current()->PostTask(
470         FROM_HERE,
471         base::Bind(&HttpStreamFactoryImpl::Job::OnCertificateErrorCallback,
472                    ptr_factory_.GetWeakPtr(), result, ssl_info_));
473     return ERR_IO_PENDING;
474   }
475
476   switch (result) {
477     case ERR_PROXY_AUTH_REQUESTED: {
478       UMA_HISTOGRAM_BOOLEAN("Net.ProxyAuthRequested.HasConnection",
479                             connection_.get() != NULL);
480       if (!connection_.get())
481         return ERR_PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION;
482       CHECK(connection_->socket());
483       CHECK(establishing_tunnel_);
484
485       next_state_ = STATE_WAITING_USER_ACTION;
486       ProxyClientSocket* proxy_socket =
487           static_cast<ProxyClientSocket*>(connection_->socket());
488       base::MessageLoop::current()->PostTask(
489           FROM_HERE,
490           base::Bind(&Job::OnNeedsProxyAuthCallback, ptr_factory_.GetWeakPtr(),
491                      *proxy_socket->GetConnectResponseInfo(),
492                      proxy_socket->GetAuthController()));
493       return ERR_IO_PENDING;
494     }
495
496     case ERR_SSL_CLIENT_AUTH_CERT_NEEDED:
497       base::MessageLoop::current()->PostTask(
498           FROM_HERE,
499           base::Bind(&Job::OnNeedsClientAuthCallback, ptr_factory_.GetWeakPtr(),
500                      connection_->ssl_error_response_info().cert_request_info));
501       return ERR_IO_PENDING;
502
503     case ERR_HTTPS_PROXY_TUNNEL_RESPONSE: {
504       DCHECK(connection_.get());
505       DCHECK(connection_->socket());
506       DCHECK(establishing_tunnel_);
507
508       ProxyClientSocket* proxy_socket =
509           static_cast<ProxyClientSocket*>(connection_->socket());
510       base::MessageLoop::current()->PostTask(
511           FROM_HERE,
512           base::Bind(&Job::OnHttpsProxyTunnelResponseCallback,
513                      ptr_factory_.GetWeakPtr(),
514                      *proxy_socket->GetConnectResponseInfo(),
515                      proxy_socket->CreateConnectResponseStream()));
516       return ERR_IO_PENDING;
517     }
518
519     case OK:
520       job_status_ = STATUS_SUCCEEDED;
521       MaybeMarkAlternateProtocolBroken();
522       next_state_ = STATE_DONE;
523       if (new_spdy_session_.get()) {
524         base::MessageLoop::current()->PostTask(
525             FROM_HERE,
526             base::Bind(&Job::OnNewSpdySessionReadyCallback,
527                        ptr_factory_.GetWeakPtr()));
528       } else if (stream_factory_->for_websockets_) {
529         DCHECK(websocket_stream_);
530         base::MessageLoop::current()->PostTask(
531             FROM_HERE,
532             base::Bind(&Job::OnWebSocketHandshakeStreamReadyCallback,
533                        ptr_factory_.GetWeakPtr()));
534       } else {
535         DCHECK(stream_.get());
536         base::MessageLoop::current()->PostTask(
537             FROM_HERE,
538             base::Bind(&Job::OnStreamReadyCallback, ptr_factory_.GetWeakPtr()));
539       }
540       return ERR_IO_PENDING;
541
542     default:
543       if (job_status_ != STATUS_BROKEN) {
544         DCHECK_EQ(STATUS_RUNNING, job_status_);
545         job_status_ = STATUS_FAILED;
546         MaybeMarkAlternateProtocolBroken();
547       }
548       base::MessageLoop::current()->PostTask(
549           FROM_HERE,
550           base::Bind(&Job::OnStreamFailedCallback, ptr_factory_.GetWeakPtr(),
551                      result));
552       return ERR_IO_PENDING;
553   }
554 }
555
556 int HttpStreamFactoryImpl::Job::DoLoop(int result) {
557   DCHECK_NE(next_state_, STATE_NONE);
558   int rv = result;
559   do {
560     State state = next_state_;
561     next_state_ = STATE_NONE;
562     switch (state) {
563       case STATE_START:
564         DCHECK_EQ(OK, rv);
565         rv = DoStart();
566         break;
567       case STATE_RESOLVE_PROXY:
568         DCHECK_EQ(OK, rv);
569         rv = DoResolveProxy();
570         break;
571       case STATE_RESOLVE_PROXY_COMPLETE:
572         rv = DoResolveProxyComplete(rv);
573         break;
574       case STATE_WAIT_FOR_JOB:
575         DCHECK_EQ(OK, rv);
576         rv = DoWaitForJob();
577         break;
578       case STATE_WAIT_FOR_JOB_COMPLETE:
579         rv = DoWaitForJobComplete(rv);
580         break;
581       case STATE_INIT_CONNECTION:
582         DCHECK_EQ(OK, rv);
583         rv = DoInitConnection();
584         break;
585       case STATE_INIT_CONNECTION_COMPLETE:
586         rv = DoInitConnectionComplete(rv);
587         break;
588       case STATE_WAITING_USER_ACTION:
589         rv = DoWaitingUserAction(rv);
590         break;
591       case STATE_RESTART_TUNNEL_AUTH:
592         DCHECK_EQ(OK, rv);
593         rv = DoRestartTunnelAuth();
594         break;
595       case STATE_RESTART_TUNNEL_AUTH_COMPLETE:
596         rv = DoRestartTunnelAuthComplete(rv);
597         break;
598       case STATE_CREATE_STREAM:
599         DCHECK_EQ(OK, rv);
600         rv = DoCreateStream();
601         break;
602       case STATE_CREATE_STREAM_COMPLETE:
603         rv = DoCreateStreamComplete(rv);
604         break;
605       default:
606         NOTREACHED() << "bad state";
607         rv = ERR_FAILED;
608         break;
609     }
610   } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
611   return rv;
612 }
613
614 int HttpStreamFactoryImpl::Job::StartInternal() {
615   CHECK_EQ(STATE_NONE, next_state_);
616   next_state_ = STATE_START;
617   int rv = RunLoop(OK);
618   DCHECK_EQ(ERR_IO_PENDING, rv);
619   return rv;
620 }
621
622 int HttpStreamFactoryImpl::Job::DoStart() {
623   int port = request_info_.url.EffectiveIntPort();
624   origin_ = HostPortPair(request_info_.url.HostNoBrackets(), port);
625   origin_url_ = stream_factory_->ApplyHostMappingRules(
626       request_info_.url, &origin_);
627
628   net_log_.BeginEvent(NetLog::TYPE_HTTP_STREAM_JOB,
629                       base::Bind(&NetLogHttpStreamJobCallback,
630                                  &request_info_.url, &origin_url_,
631                                  priority_));
632
633   // Don't connect to restricted ports.
634   bool is_port_allowed = IsPortAllowedByDefault(port);
635   if (request_info_.url.SchemeIs("ftp")) {
636     // Never share connection with other jobs for FTP requests.
637     DCHECK(!waiting_job_);
638
639     is_port_allowed = IsPortAllowedByFtp(port);
640   }
641   if (!is_port_allowed && !IsPortAllowedByOverride(port)) {
642     if (waiting_job_) {
643       waiting_job_->Resume(this);
644       waiting_job_ = NULL;
645     }
646     return ERR_UNSAFE_PORT;
647   }
648
649   next_state_ = STATE_RESOLVE_PROXY;
650   return OK;
651 }
652
653 int HttpStreamFactoryImpl::Job::DoResolveProxy() {
654   DCHECK(!pac_request_);
655
656   next_state_ = STATE_RESOLVE_PROXY_COMPLETE;
657
658   if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
659     proxy_info_.UseDirect();
660     return OK;
661   }
662
663   return session_->proxy_service()->ResolveProxy(
664       request_info_.url, &proxy_info_, io_callback_, &pac_request_, net_log_);
665 }
666
667 int HttpStreamFactoryImpl::Job::DoResolveProxyComplete(int result) {
668   pac_request_ = NULL;
669
670   if (result == OK) {
671     // Remove unsupported proxies from the list.
672     proxy_info_.RemoveProxiesWithoutScheme(
673         ProxyServer::SCHEME_DIRECT | ProxyServer::SCHEME_QUIC |
674         ProxyServer::SCHEME_HTTP | ProxyServer::SCHEME_HTTPS |
675         ProxyServer::SCHEME_SOCKS4 | ProxyServer::SCHEME_SOCKS5);
676
677     if (proxy_info_.is_empty()) {
678       // No proxies/direct to choose from. This happens when we don't support
679       // any of the proxies in the returned list.
680       result = ERR_NO_SUPPORTED_PROXIES;
681     } else if (using_quic_ &&
682                (!proxy_info_.is_quic() && !proxy_info_.is_direct())) {
683       // QUIC can not be spoken to non-QUIC proxies.  This error should not be
684       // user visible, because the non-alternate job should be resumed.
685       result = ERR_NO_SUPPORTED_PROXIES;
686     }
687   }
688
689   if (result != OK) {
690     if (waiting_job_) {
691       waiting_job_->Resume(this);
692       waiting_job_ = NULL;
693     }
694     return result;
695   }
696
697   if (blocking_job_)
698     next_state_ = STATE_WAIT_FOR_JOB;
699   else
700     next_state_ = STATE_INIT_CONNECTION;
701   return OK;
702 }
703
704 bool HttpStreamFactoryImpl::Job::ShouldForceSpdySSL() const {
705   bool rv = session_->params().force_spdy_always &&
706       session_->params().force_spdy_over_ssl;
707   return rv && !session_->HasSpdyExclusion(origin_);
708 }
709
710 bool HttpStreamFactoryImpl::Job::ShouldForceSpdyWithoutSSL() const {
711   bool rv = session_->params().force_spdy_always &&
712       !session_->params().force_spdy_over_ssl;
713   return rv && !session_->HasSpdyExclusion(origin_);
714 }
715
716 bool HttpStreamFactoryImpl::Job::ShouldForceQuic() const {
717   return session_->params().enable_quic &&
718     session_->params().origin_to_force_quic_on.Equals(origin_) &&
719     proxy_info_.is_direct();
720 }
721
722 int HttpStreamFactoryImpl::Job::DoWaitForJob() {
723   DCHECK(blocking_job_);
724   next_state_ = STATE_WAIT_FOR_JOB_COMPLETE;
725   return ERR_IO_PENDING;
726 }
727
728 int HttpStreamFactoryImpl::Job::DoWaitForJobComplete(int result) {
729   DCHECK(!blocking_job_);
730   DCHECK_EQ(OK, result);
731   next_state_ = STATE_INIT_CONNECTION;
732   return OK;
733 }
734
735 int HttpStreamFactoryImpl::Job::DoInitConnection() {
736   DCHECK(!blocking_job_);
737   DCHECK(!connection_->is_initialized());
738   DCHECK(proxy_info_.proxy_server().is_valid());
739   next_state_ = STATE_INIT_CONNECTION_COMPLETE;
740
741   using_ssl_ = request_info_.url.SchemeIs("https") ||
742       request_info_.url.SchemeIs("wss") || ShouldForceSpdySSL();
743   using_spdy_ = false;
744
745   if (ShouldForceQuic())
746     using_quic_ = true;
747
748   if (proxy_info_.is_quic())
749     using_quic_ = true;
750
751   if (using_quic_) {
752     DCHECK(session_->params().enable_quic);
753     if (proxy_info_.is_quic() && !request_info_.url.SchemeIs("http")) {
754       NOTREACHED();
755       // TODO(rch): support QUIC proxies for HTTPS urls.
756       return ERR_NOT_IMPLEMENTED;
757     }
758     HostPortPair destination = proxy_info_.is_quic() ?
759         proxy_info_.proxy_server().host_port_pair() : origin_;
760     next_state_ = STATE_INIT_CONNECTION_COMPLETE;
761     bool secure_quic = using_ssl_ || proxy_info_.is_quic();
762     int rv = quic_request_.Request(
763         destination, secure_quic, request_info_.privacy_mode,
764         request_info_.method, net_log_, io_callback_);
765     if (rv == OK) {
766       using_existing_quic_session_ = true;
767     } else {
768       // OK, there's no available QUIC session. Let |waiting_job_| resume
769       // if it's paused.
770       if (waiting_job_) {
771         waiting_job_->Resume(this);
772         waiting_job_ = NULL;
773       }
774     }
775     return rv;
776   }
777
778   // Check first if we have a spdy session for this group.  If so, then go
779   // straight to using that.
780   SpdySessionKey spdy_session_key = GetSpdySessionKey();
781   base::WeakPtr<SpdySession> spdy_session =
782       session_->spdy_session_pool()->FindAvailableSession(
783           spdy_session_key, net_log_);
784   if (spdy_session && CanUseExistingSpdySession()) {
785     // If we're preconnecting, but we already have a SpdySession, we don't
786     // actually need to preconnect any sockets, so we're done.
787     if (IsPreconnecting())
788       return OK;
789     using_spdy_ = true;
790     next_state_ = STATE_CREATE_STREAM;
791     existing_spdy_session_ = spdy_session;
792     return OK;
793   } else if (request_ && !request_->HasSpdySessionKey() &&
794              (using_ssl_ || ShouldForceSpdyWithoutSSL())) {
795     // Update the spdy session key for the request that launched this job.
796     request_->SetSpdySessionKey(spdy_session_key);
797   }
798
799   // OK, there's no available SPDY session. Let |waiting_job_| resume if it's
800   // paused.
801
802   if (waiting_job_) {
803     waiting_job_->Resume(this);
804     waiting_job_ = NULL;
805   }
806
807   if (proxy_info_.is_http() || proxy_info_.is_https())
808     establishing_tunnel_ = using_ssl_;
809
810   bool want_spdy_over_npn = original_url_ != NULL;
811
812   if (proxy_info_.is_https()) {
813     InitSSLConfig(proxy_info_.proxy_server().host_port_pair(),
814                   &proxy_ssl_config_,
815                   true /* is a proxy server */);
816     // Disable revocation checking for HTTPS proxies since the revocation
817     // requests are probably going to need to go through the proxy too.
818     proxy_ssl_config_.rev_checking_enabled = false;
819   }
820   if (using_ssl_) {
821     InitSSLConfig(origin_, &server_ssl_config_,
822                   false /* not a proxy server */);
823   }
824
825   if (IsPreconnecting()) {
826     DCHECK(!stream_factory_->for_websockets_);
827     return PreconnectSocketsForHttpRequest(
828         origin_url_,
829         request_info_.extra_headers,
830         request_info_.load_flags,
831         priority_,
832         session_,
833         proxy_info_,
834         ShouldForceSpdySSL(),
835         want_spdy_over_npn,
836         server_ssl_config_,
837         proxy_ssl_config_,
838         request_info_.privacy_mode,
839         net_log_,
840         num_streams_);
841   }
842
843   // If we can't use a SPDY session, don't both checking for one after
844   // the hostname is resolved.
845   OnHostResolutionCallback resolution_callback = CanUseExistingSpdySession() ?
846       base::Bind(&Job::OnHostResolution, session_->spdy_session_pool(),
847                  GetSpdySessionKey()) :
848       OnHostResolutionCallback();
849   if (stream_factory_->for_websockets_) {
850     // TODO(ricea): Re-enable NPN when WebSockets over SPDY is supported.
851     SSLConfig websocket_server_ssl_config = server_ssl_config_;
852     websocket_server_ssl_config.next_protos.clear();
853     return InitSocketHandleForWebSocketRequest(
854         origin_url_, request_info_.extra_headers, request_info_.load_flags,
855         priority_, session_, proxy_info_, ShouldForceSpdySSL(),
856         want_spdy_over_npn, websocket_server_ssl_config, proxy_ssl_config_,
857         request_info_.privacy_mode, net_log_,
858         connection_.get(), resolution_callback, io_callback_);
859   }
860
861   return InitSocketHandleForHttpRequest(
862       origin_url_, request_info_.extra_headers, request_info_.load_flags,
863       priority_, session_, proxy_info_, ShouldForceSpdySSL(),
864       want_spdy_over_npn, server_ssl_config_, proxy_ssl_config_,
865       request_info_.privacy_mode, net_log_,
866       connection_.get(), resolution_callback, io_callback_);
867 }
868
869 int HttpStreamFactoryImpl::Job::DoInitConnectionComplete(int result) {
870   if (IsPreconnecting()) {
871     if (using_quic_)
872       return result;
873     DCHECK_EQ(OK, result);
874     return OK;
875   }
876
877   if (result == ERR_SPDY_SESSION_ALREADY_EXISTS) {
878     // We found a SPDY connection after resolving the host.  This is
879     // probably an IP pooled connection.
880     SpdySessionKey spdy_session_key = GetSpdySessionKey();
881     existing_spdy_session_ =
882         session_->spdy_session_pool()->FindAvailableSession(
883             spdy_session_key, net_log_);
884     if (existing_spdy_session_) {
885       using_spdy_ = true;
886       next_state_ = STATE_CREATE_STREAM;
887     } else {
888       // It is possible that the spdy session no longer exists.
889       ReturnToStateInitConnection(true /* close connection */);
890     }
891     return OK;
892   }
893
894   // TODO(willchan): Make this a bit more exact. Maybe there are recoverable
895   // errors, such as ignoring certificate errors for Alternate-Protocol.
896   if (result < 0 && waiting_job_) {
897     waiting_job_->Resume(this);
898     waiting_job_ = NULL;
899   }
900
901   // |result| may be the result of any of the stacked pools. The following
902   // logic is used when determining how to interpret an error.
903   // If |result| < 0:
904   //   and connection_->socket() != NULL, then the SSL handshake ran and it
905   //     is a potentially recoverable error.
906   //   and connection_->socket == NULL and connection_->is_ssl_error() is true,
907   //     then the SSL handshake ran with an unrecoverable error.
908   //   otherwise, the error came from one of the other pools.
909   bool ssl_started = using_ssl_ && (result == OK || connection_->socket() ||
910                                     connection_->is_ssl_error());
911
912   if (ssl_started && (result == OK || IsCertificateError(result))) {
913     if (using_quic_ && result == OK) {
914       was_npn_negotiated_ = true;
915       NextProto protocol_negotiated =
916           SSLClientSocket::NextProtoFromString("quic/1+spdy/3");
917       protocol_negotiated_ = protocol_negotiated;
918     } else {
919       SSLClientSocket* ssl_socket =
920           static_cast<SSLClientSocket*>(connection_->socket());
921       if (ssl_socket->WasNpnNegotiated()) {
922         was_npn_negotiated_ = true;
923         std::string proto;
924         std::string server_protos;
925         SSLClientSocket::NextProtoStatus status =
926             ssl_socket->GetNextProto(&proto, &server_protos);
927         NextProto protocol_negotiated =
928             SSLClientSocket::NextProtoFromString(proto);
929         protocol_negotiated_ = protocol_negotiated;
930         net_log_.AddEvent(
931             NetLog::TYPE_HTTP_STREAM_REQUEST_PROTO,
932             base::Bind(&NetLogHttpStreamProtoCallback,
933                        status, &proto, &server_protos));
934         if (ssl_socket->was_spdy_negotiated())
935           SwitchToSpdyMode();
936       }
937       if (ShouldForceSpdySSL())
938         SwitchToSpdyMode();
939     }
940   } else if (proxy_info_.is_https() && connection_->socket() &&
941         result == OK) {
942     ProxyClientSocket* proxy_socket =
943       static_cast<ProxyClientSocket*>(connection_->socket());
944     if (proxy_socket->IsUsingSpdy()) {
945       was_npn_negotiated_ = true;
946       protocol_negotiated_ = proxy_socket->GetProtocolNegotiated();
947       SwitchToSpdyMode();
948     }
949   }
950
951   // We may be using spdy without SSL
952   if (ShouldForceSpdyWithoutSSL())
953     SwitchToSpdyMode();
954
955   if (result == ERR_PROXY_AUTH_REQUESTED ||
956       result == ERR_HTTPS_PROXY_TUNNEL_RESPONSE) {
957     DCHECK(!ssl_started);
958     // Other state (i.e. |using_ssl_|) suggests that |connection_| will have an
959     // SSL socket, but there was an error before that could happen.  This
960     // puts the in progress HttpProxy socket into |connection_| in order to
961     // complete the auth (or read the response body).  The tunnel restart code
962     // is careful to remove it before returning control to the rest of this
963     // class.
964     connection_.reset(connection_->release_pending_http_proxy_connection());
965     return result;
966   }
967
968   if (!ssl_started && result < 0 && original_url_.get()) {
969     job_status_ = STATUS_BROKEN;
970     MaybeMarkAlternateProtocolBroken();
971     return result;
972   }
973
974   if (using_quic_) {
975     if (result < 0) {
976       job_status_ = STATUS_BROKEN;
977       MaybeMarkAlternateProtocolBroken();
978       return result;
979     }
980     stream_ = quic_request_.ReleaseStream();
981     next_state_ = STATE_NONE;
982     return OK;
983   }
984
985   if (result < 0 && !ssl_started)
986     return ReconsiderProxyAfterError(result);
987   establishing_tunnel_ = false;
988
989   if (connection_->socket()) {
990     LogHttpConnectedMetrics(*connection_);
991
992     // We officially have a new connection.  Record the type.
993     if (!connection_->is_reused()) {
994       ConnectionType type = using_spdy_ ? CONNECTION_SPDY : CONNECTION_HTTP;
995       UpdateConnectionTypeHistograms(type);
996     }
997   }
998
999   // Handle SSL errors below.
1000   if (using_ssl_) {
1001     DCHECK(ssl_started);
1002     if (IsCertificateError(result)) {
1003       if (using_spdy_ && original_url_.get() &&
1004           original_url_->SchemeIs("http")) {
1005         // We ignore certificate errors for http over spdy.
1006         spdy_certificate_error_ = result;
1007         result = OK;
1008       } else {
1009         result = HandleCertificateError(result);
1010         if (result == OK && !connection_->socket()->IsConnectedAndIdle()) {
1011           ReturnToStateInitConnection(true /* close connection */);
1012           return result;
1013         }
1014       }
1015     }
1016     if (result < 0)
1017       return result;
1018   }
1019
1020   next_state_ = STATE_CREATE_STREAM;
1021   return OK;
1022 }
1023
1024 int HttpStreamFactoryImpl::Job::DoWaitingUserAction(int result) {
1025   // This state indicates that the stream request is in a partially
1026   // completed state, and we've called back to the delegate for more
1027   // information.
1028
1029   // We're always waiting here for the delegate to call us back.
1030   return ERR_IO_PENDING;
1031 }
1032
1033 int HttpStreamFactoryImpl::Job::DoCreateStream() {
1034   DCHECK(connection_->socket() || existing_spdy_session_.get() || using_quic_);
1035
1036   next_state_ = STATE_CREATE_STREAM_COMPLETE;
1037
1038   // We only set the socket motivation if we're the first to use
1039   // this socket.  Is there a race for two SPDY requests?  We really
1040   // need to plumb this through to the connect level.
1041   if (connection_->socket() && !connection_->is_reused())
1042     SetSocketMotivation();
1043
1044   if (!using_spdy_) {
1045     // We may get ftp scheme when fetching ftp resources through proxy.
1046     bool using_proxy = (proxy_info_.is_http() || proxy_info_.is_https()) &&
1047                        (request_info_.url.SchemeIs("http") ||
1048                         request_info_.url.SchemeIs("ftp"));
1049     if (stream_factory_->for_websockets_) {
1050       DCHECK(request_);
1051       DCHECK(request_->websocket_handshake_stream_create_helper());
1052       websocket_stream_.reset(
1053           request_->websocket_handshake_stream_create_helper()
1054               ->CreateBasicStream(connection_.Pass(), using_proxy));
1055     } else {
1056       stream_.reset(new HttpBasicStream(connection_.release(), using_proxy));
1057     }
1058     return OK;
1059   }
1060
1061   CHECK(!stream_.get());
1062
1063   bool direct = true;
1064   const ProxyServer& proxy_server = proxy_info_.proxy_server();
1065   PrivacyMode privacy_mode = request_info_.privacy_mode;
1066   SpdySessionKey spdy_session_key(origin_, proxy_server, privacy_mode);
1067   if (IsHttpsProxyAndHttpUrl()) {
1068     // If we don't have a direct SPDY session, and we're using an HTTPS
1069     // proxy, then we might have a SPDY session to the proxy.
1070     // We never use privacy mode for connection to proxy server.
1071     spdy_session_key = SpdySessionKey(proxy_server.host_port_pair(),
1072                                       ProxyServer::Direct(),
1073                                       PRIVACY_MODE_DISABLED);
1074     direct = false;
1075   }
1076
1077   base::WeakPtr<SpdySession> spdy_session;
1078   if (existing_spdy_session_.get()) {
1079     // We picked up an existing session, so we don't need our socket.
1080     if (connection_->socket())
1081       connection_->socket()->Disconnect();
1082     connection_->Reset();
1083     std::swap(spdy_session, existing_spdy_session_);
1084   } else {
1085     SpdySessionPool* spdy_pool = session_->spdy_session_pool();
1086     spdy_session = spdy_pool->FindAvailableSession(spdy_session_key, net_log_);
1087     if (!spdy_session) {
1088       base::WeakPtr<SpdySession> new_spdy_session =
1089           spdy_pool->CreateAvailableSessionFromSocket(spdy_session_key,
1090                                                       connection_.Pass(),
1091                                                       net_log_,
1092                                                       spdy_certificate_error_,
1093                                                       using_ssl_);
1094       if (!new_spdy_session->HasAcceptableTransportSecurity()) {
1095         new_spdy_session->CloseSessionOnError(
1096             ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY, "");
1097         return ERR_SPDY_INADEQUATE_TRANSPORT_SECURITY;
1098       }
1099
1100       new_spdy_session_ = new_spdy_session;
1101       spdy_session_direct_ = direct;
1102       const HostPortPair& host_port_pair = spdy_session_key.host_port_pair();
1103       base::WeakPtr<HttpServerProperties> http_server_properties =
1104           session_->http_server_properties();
1105       if (http_server_properties)
1106         http_server_properties->SetSupportsSpdy(host_port_pair, true);
1107
1108       // Create a SpdyHttpStream attached to the session;
1109       // OnNewSpdySessionReadyCallback is not called until an event loop
1110       // iteration later, so if the SpdySession is closed between then, allow
1111       // reuse state from the underlying socket, sampled by SpdyHttpStream,
1112       // bubble up to the request.
1113       bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1114       stream_.reset(new SpdyHttpStream(new_spdy_session_, use_relative_url));
1115
1116       return OK;
1117     }
1118   }
1119
1120   if (!spdy_session)
1121     return ERR_CONNECTION_CLOSED;
1122
1123   // TODO(willchan): Delete this code, because eventually, the
1124   // HttpStreamFactoryImpl will be creating all the SpdyHttpStreams, since it
1125   // will know when SpdySessions become available.
1126
1127   // TODO(ricea): Restore the code for WebSockets over SPDY once it's
1128   // implemented.
1129   if (stream_factory_->for_websockets_)
1130     return ERR_NOT_IMPLEMENTED;
1131
1132   bool use_relative_url = direct || request_info_.url.SchemeIs("https");
1133   stream_.reset(new SpdyHttpStream(spdy_session, use_relative_url));
1134
1135   return OK;
1136 }
1137
1138 int HttpStreamFactoryImpl::Job::DoCreateStreamComplete(int result) {
1139   if (result < 0)
1140     return result;
1141
1142   session_->proxy_service()->ReportSuccess(proxy_info_);
1143   next_state_ = STATE_NONE;
1144   return OK;
1145 }
1146
1147 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuth() {
1148   next_state_ = STATE_RESTART_TUNNEL_AUTH_COMPLETE;
1149   ProxyClientSocket* proxy_socket =
1150       static_cast<ProxyClientSocket*>(connection_->socket());
1151   return proxy_socket->RestartWithAuth(io_callback_);
1152 }
1153
1154 int HttpStreamFactoryImpl::Job::DoRestartTunnelAuthComplete(int result) {
1155   if (result == ERR_PROXY_AUTH_REQUESTED)
1156     return result;
1157
1158   if (result == OK) {
1159     // Now that we've got the HttpProxyClientSocket connected.  We have
1160     // to release it as an idle socket into the pool and start the connection
1161     // process from the beginning.  Trying to pass it in with the
1162     // SSLSocketParams might cause a deadlock since params are dispatched
1163     // interchangeably.  This request won't necessarily get this http proxy
1164     // socket, but there will be forward progress.
1165     establishing_tunnel_ = false;
1166     ReturnToStateInitConnection(false /* do not close connection */);
1167     return OK;
1168   }
1169
1170   return ReconsiderProxyAfterError(result);
1171 }
1172
1173 void HttpStreamFactoryImpl::Job::ReturnToStateInitConnection(
1174     bool close_connection) {
1175   if (close_connection && connection_->socket())
1176     connection_->socket()->Disconnect();
1177   connection_->Reset();
1178
1179   if (request_)
1180     request_->RemoveRequestFromSpdySessionRequestMap();
1181
1182   next_state_ = STATE_INIT_CONNECTION;
1183 }
1184
1185 void HttpStreamFactoryImpl::Job::SetSocketMotivation() {
1186   if (request_info_.motivation == HttpRequestInfo::PRECONNECT_MOTIVATED)
1187     connection_->socket()->SetSubresourceSpeculation();
1188   else if (request_info_.motivation == HttpRequestInfo::OMNIBOX_MOTIVATED)
1189     connection_->socket()->SetOmniboxSpeculation();
1190   // TODO(mbelshe): Add other motivations (like EARLY_LOAD_MOTIVATED).
1191 }
1192
1193 bool HttpStreamFactoryImpl::Job::IsHttpsProxyAndHttpUrl() const {
1194   if (!proxy_info_.is_https())
1195     return false;
1196   if (original_url_.get()) {
1197     // We currently only support Alternate-Protocol where the original scheme
1198     // is http.
1199     DCHECK(original_url_->SchemeIs("http"));
1200     return original_url_->SchemeIs("http");
1201   }
1202   return request_info_.url.SchemeIs("http");
1203 }
1204
1205 // Sets several fields of ssl_config for the given origin_server based on the
1206 // proxy info and other factors.
1207 void HttpStreamFactoryImpl::Job::InitSSLConfig(
1208     const HostPortPair& origin_server,
1209     SSLConfig* ssl_config,
1210     bool is_proxy) const {
1211   if (proxy_info_.is_https() && ssl_config->send_client_cert) {
1212     // When connecting through an HTTPS proxy, disable TLS False Start so
1213     // that client authentication errors can be distinguished between those
1214     // originating from the proxy server (ERR_PROXY_CONNECTION_FAILED) and
1215     // those originating from the endpoint (ERR_SSL_PROTOCOL_ERROR /
1216     // ERR_BAD_SSL_CLIENT_AUTH_CERT).
1217     // TODO(rch): This assumes that the HTTPS proxy will only request a
1218     // client certificate during the initial handshake.
1219     // http://crbug.com/59292
1220     ssl_config->false_start_enabled = false;
1221   }
1222
1223   enum {
1224     FALLBACK_NONE = 0,    // SSL version fallback did not occur.
1225     FALLBACK_SSL3 = 1,    // Fell back to SSL 3.0.
1226     FALLBACK_TLS1 = 2,    // Fell back to TLS 1.0.
1227     FALLBACK_TLS1_1 = 3,  // Fell back to TLS 1.1.
1228     FALLBACK_MAX
1229   };
1230
1231   int fallback = FALLBACK_NONE;
1232   if (ssl_config->version_fallback) {
1233     switch (ssl_config->version_max) {
1234       case SSL_PROTOCOL_VERSION_SSL3:
1235         fallback = FALLBACK_SSL3;
1236         break;
1237       case SSL_PROTOCOL_VERSION_TLS1:
1238         fallback = FALLBACK_TLS1;
1239         break;
1240       case SSL_PROTOCOL_VERSION_TLS1_1:
1241         fallback = FALLBACK_TLS1_1;
1242         break;
1243     }
1244   }
1245   UMA_HISTOGRAM_ENUMERATION("Net.ConnectionUsedSSLVersionFallback",
1246                             fallback, FALLBACK_MAX);
1247
1248   // We also wish to measure the amount of fallback connections for a host that
1249   // we know implements TLS up to 1.2. Ideally there would be no fallback here
1250   // but high numbers of SSLv3 would suggest that SSLv3 fallback is being
1251   // caused by network middleware rather than buggy HTTPS servers.
1252   const std::string& host = origin_server.host();
1253   if (!is_proxy &&
1254       host.size() >= 10 &&
1255       host.compare(host.size() - 10, 10, "google.com") == 0 &&
1256       (host.size() == 10 || host[host.size()-11] == '.')) {
1257     UMA_HISTOGRAM_ENUMERATION("Net.GoogleConnectionUsedSSLVersionFallback",
1258                               fallback, FALLBACK_MAX);
1259   }
1260
1261   if (request_info_.load_flags & LOAD_VERIFY_EV_CERT)
1262     ssl_config->verify_ev_cert = true;
1263
1264   // Disable Channel ID if privacy mode is enabled.
1265   if (request_info_.privacy_mode == PRIVACY_MODE_ENABLED)
1266     ssl_config->channel_id_enabled = false;
1267 }
1268
1269
1270 int HttpStreamFactoryImpl::Job::ReconsiderProxyAfterError(int error) {
1271   DCHECK(!pac_request_);
1272
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.
1275   //
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.
1280   //
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).
1305       //
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;
1313   }
1314
1315   if (request_info_.load_flags & LOAD_BYPASS_PROXY) {
1316     return error;
1317   }
1318
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());
1322   }
1323
1324   int rv = session_->proxy_service()->ReconsiderProxyAfterError(
1325       request_info_.url, error, &proxy_info_, io_callback_, &pac_request_,
1326       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;
1342   }
1343
1344   return rv;
1345 }
1346
1347 int HttpStreamFactoryImpl::Job::HandleCertificateError(int error) {
1348   DCHECK(using_ssl_);
1349   DCHECK(IsCertificateError(error));
1350
1351   SSLClientSocket* ssl_socket =
1352       static_cast<SSLClientSocket*>(connection_->socket());
1353   ssl_socket->GetSSLInfo(&ssl_info_);
1354
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;
1360
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;
1368   }
1369   bad_cert.cert_status = ssl_info_.cert_status;
1370   server_ssl_config_.allowed_bad_certs.push_back(bad_cert);
1371
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;
1378 }
1379
1380 void HttpStreamFactoryImpl::Job::SwitchToSpdyMode() {
1381   if (HttpStreamFactory::spdy_enabled())
1382     using_spdy_ = true;
1383 }
1384
1385 // static
1386 void HttpStreamFactoryImpl::Job::LogHttpConnectedMetrics(
1387     const ClientSocketHandle& handle) {
1388   UMA_HISTOGRAM_ENUMERATION("Net.HttpSocketType", handle.reuse_type(),
1389                             ClientSocketHandle::NUM_TYPES);
1390
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;
1416   }
1417 }
1418
1419 bool HttpStreamFactoryImpl::Job::IsPreconnecting() const {
1420   DCHECK_GE(num_streams_, 0);
1421   return num_streams_ > 0;
1422 }
1423
1424 bool HttpStreamFactoryImpl::Job::IsOrphaned() const {
1425   return !IsPreconnecting() && !request_;
1426 }
1427
1428 void HttpStreamFactoryImpl::Job::ReportJobSuccededForRequest() {
1429   net::AlternateProtocolExperiment alternate_protocol_experiment =
1430       ALTERNATE_PROTOCOL_NOT_PART_OF_EXPERIMENT;
1431   base::WeakPtr<HttpServerProperties> http_server_properties =
1432       session_->http_server_properties();
1433   if (http_server_properties) {
1434     alternate_protocol_experiment =
1435         http_server_properties->GetAlternateProtocolExperiment();
1436   }
1437   if (using_existing_quic_session_) {
1438     // If an existing session was used, then no TCP connection was
1439     // started.
1440     HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_NO_RACE,
1441                                     alternate_protocol_experiment);
1442   } else if (original_url_) {
1443     // This job was the alternate protocol job, and hence won the race.
1444     HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_WON_RACE,
1445                                     alternate_protocol_experiment);
1446   } else {
1447     // This job was the normal job, and hence the alternate protocol job lost
1448     // the race.
1449     HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_LOST_RACE,
1450                                     alternate_protocol_experiment);
1451   }
1452 }
1453
1454 void HttpStreamFactoryImpl::Job::MarkOtherJobComplete(const Job& job) {
1455   DCHECK_EQ(STATUS_RUNNING, other_job_status_);
1456   other_job_status_ = job.job_status_;
1457   MaybeMarkAlternateProtocolBroken();
1458 }
1459
1460 void HttpStreamFactoryImpl::Job::MaybeMarkAlternateProtocolBroken() {
1461   if (job_status_ == STATUS_RUNNING || other_job_status_ == STATUS_RUNNING)
1462     return;
1463
1464   bool is_alternate_protocol_job = original_url_.get() != NULL;
1465   if (is_alternate_protocol_job) {
1466     if (job_status_ == STATUS_BROKEN && other_job_status_ == STATUS_SUCCEEDED) {
1467       HistogramBrokenAlternateProtocolLocation(
1468           BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_ALT);
1469       session_->http_server_properties()->SetBrokenAlternateProtocol(
1470           HostPortPair::FromURL(*original_url_));
1471     }
1472     return;
1473   }
1474
1475   if (job_status_ == STATUS_SUCCEEDED && other_job_status_ == STATUS_BROKEN) {
1476     HistogramBrokenAlternateProtocolLocation(
1477         BROKEN_ALTERNATE_PROTOCOL_LOCATION_HTTP_STREAM_FACTORY_IMPL_JOB_MAIN);
1478     session_->http_server_properties()->SetBrokenAlternateProtocol(
1479         HostPortPair::FromURL(request_info_.url));
1480   }
1481 }
1482
1483 }  // namespace net