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 #ifndef NET_HTTP_HTTP_STREAM_FACTORY_IMPL_JOB_H_
6 #define NET_HTTP_HTTP_STREAM_FACTORY_IMPL_JOB_H_
8 #include "base/memory/ref_counted.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/memory/weak_ptr.h"
11 #include "net/base/completion_callback.h"
12 #include "net/base/request_priority.h"
13 #include "net/http/http_auth.h"
14 #include "net/http/http_auth_controller.h"
15 #include "net/http/http_request_info.h"
16 #include "net/http/http_stream_factory_impl.h"
17 #include "net/log/net_log.h"
18 #include "net/proxy/proxy_service.h"
19 #include "net/quic/quic_stream_factory.h"
20 #include "net/socket/client_socket_handle.h"
21 #include "net/socket/client_socket_pool_manager.h"
22 #include "net/socket/ssl_client_socket.h"
23 #include "net/spdy/spdy_session_key.h"
24 #include "net/ssl/ssl_config_service.h"
28 class ClientSocketHandle
;
29 class HttpAuthController
;
30 class HttpNetworkSession
;
32 class SpdySessionPool
;
35 // An HttpStreamRequestImpl exists for each stream which is in progress of being
36 // created for the StreamFactory.
37 class HttpStreamFactoryImpl::Job
{
39 Job(HttpStreamFactoryImpl
* stream_factory
,
40 HttpNetworkSession
* session
,
41 const HttpRequestInfo
& request_info
,
42 RequestPriority priority
,
43 const SSLConfig
& server_ssl_config
,
44 const SSLConfig
& proxy_ssl_config
,
48 // Start initiates the process of creating a new HttpStream. |request| will be
49 // notified upon completion if the Job has not been Orphan()'d.
50 void Start(Request
* request
);
52 // Preconnect will attempt to request |num_streams| sockets from the
53 // appropriate ClientSocketPool.
54 int Preconnect(int num_streams
);
56 int RestartTunnelWithProxyAuth(const AuthCredentials
& credentials
);
57 LoadState
GetLoadState() const;
59 // Marks this Job as the "alternate" job, from Alternate-Protocol or Alt-Svc
60 // using the specified alternate service.
61 void MarkAsAlternate(AlternativeService alternative_service
);
63 // Tells |this| to wait for |job| to resume it.
64 void WaitFor(Job
* job
);
66 // Tells |this| that |job| has determined it still needs to continue
67 // connecting, so allow |this| to continue. If this is not called, then
68 // |request_| is expected to cancel |this| by deleting it.
69 void Resume(Job
* job
);
71 // Used to detach the Job from |request|.
72 void Orphan(const Request
* request
);
74 void SetPriority(RequestPriority priority
);
76 RequestPriority
priority() const { return priority_
; }
77 bool was_npn_negotiated() const;
78 NextProto
protocol_negotiated() const;
79 bool using_spdy() const;
80 const BoundNetLog
& net_log() const { return net_log_
; }
82 const SSLConfig
& server_ssl_config() const;
83 const SSLConfig
& proxy_ssl_config() const;
84 const ProxyInfo
& proxy_info() const;
86 // Indicates whether or not this job is performing a preconnect.
87 bool IsPreconnecting() const;
89 // Indicates whether or not this Job has been orphaned by a Request.
90 bool IsOrphaned() const;
92 // Called to indicate that this job succeeded, and some other jobs
94 void ReportJobSucceededForRequest();
96 // Marks that the other |job| has completed.
97 void MarkOtherJobComplete(const Job
& job
);
103 STATE_RESOLVE_PROXY_COMPLETE
,
105 // Note that when Alternate-Protocol says we can connect to an alternate
106 // port using a different protocol, we have the choice of communicating over
107 // the original protocol, or speaking the alternate protocol (currently,
108 // only npn-spdy) over an alternate port. For a cold page load, the http
109 // connection that delivers the http response that has the
110 // Alternate-Protocol header will already be warm. So, blocking the next
111 // http request on establishing a new npn-spdy connection would incur extra
112 // latency. Even if the http connection was not reused, establishing a new
113 // http connection is typically faster than npn-spdy, since npn-spdy
114 // requires a SSL handshake. Therefore, we start both the http and the
115 // npn-spdy jobs in parallel. In order not to unnecessarily waste sockets,
116 // we have the http job block on the npn-spdy job after proxy resolution.
117 // The npn-spdy job will Resume() the http job if, in
118 // STATE_INIT_CONNECTION_COMPLETE, it detects an error or does not find an
119 // existing SpdySession. In that case, the http and npn-spdy jobs will race.
121 STATE_WAIT_FOR_JOB_COMPLETE
,
123 STATE_INIT_CONNECTION
,
124 STATE_INIT_CONNECTION_COMPLETE
,
125 STATE_WAITING_USER_ACTION
,
126 STATE_RESTART_TUNNEL_AUTH
,
127 STATE_RESTART_TUNNEL_AUTH_COMPLETE
,
129 STATE_CREATE_STREAM_COMPLETE
,
130 STATE_DRAIN_BODY_FOR_AUTH_RESTART
,
131 STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
,
143 // Wrapper class for SpdySessionPool methods to enforce certificate
144 // requirements for SpdySessions.
145 class ValidSpdySessionPool
{
147 ValidSpdySessionPool(SpdySessionPool
* spdy_session_pool
,
149 bool is_spdy_alternate
);
151 // Returns OK if a SpdySession was not found (in which case |spdy_session|
152 // is set to nullptr), or if one was found (in which case |spdy_session| is
153 // set to it) and it has an associated SSL certificate with is valid for
154 // |origin_url_|, or if this requirement does not apply because the Job is
155 // not a SPDY alternate job. Returns the appropriate error code otherwise,
156 // in which case |spdy_session| should not be used.
157 int FindAvailableSession(const SpdySessionKey
& key
,
158 const BoundNetLog
& net_log
,
159 base::WeakPtr
<SpdySession
>* spdy_session
);
161 // Creates a SpdySession and sets |spdy_session| to point to it. Returns OK
162 // if the associated SSL certificate is valid for |origin_url_|, or if this
163 // requirement does not apply because the Job is not a SPDY alternate job.
164 // Returns the appropriate error code otherwise, in which case
165 // |spdy_session| should not be used.
166 int CreateAvailableSessionFromSocket(
167 const SpdySessionKey
& key
,
168 scoped_ptr
<ClientSocketHandle
> connection
,
169 const BoundNetLog
& net_log
,
170 int certificate_error_code
,
172 base::WeakPtr
<SpdySession
>* spdy_session
);
175 // Returns OK if |spdy_session| has an associated SSL certificate with is
176 // valid for |origin_url_|, or if this requirement does not apply because
177 // the Job is not a SPDY alternate job, or if |spdy_session| is null.
178 // Returns appropriate error code otherwise.
179 int CheckAlternativeServiceValidityForOrigin(
180 base::WeakPtr
<SpdySession
> spdy_session
);
182 SpdySessionPool
* const spdy_session_pool_
;
183 const GURL origin_url_
;
184 const bool is_spdy_alternate_
;
187 void OnStreamReadyCallback();
188 void OnWebSocketHandshakeStreamReadyCallback();
189 // This callback function is called when a new SPDY session is created.
190 void OnNewSpdySessionReadyCallback();
191 void OnStreamFailedCallback(int result
);
192 void OnCertificateErrorCallback(int result
, const SSLInfo
& ssl_info
);
193 void OnNeedsProxyAuthCallback(const HttpResponseInfo
& response_info
,
194 HttpAuthController
* auth_controller
);
195 void OnNeedsClientAuthCallback(SSLCertRequestInfo
* cert_info
);
196 void OnHttpsProxyTunnelResponseCallback(const HttpResponseInfo
& response_info
,
198 void OnPreconnectsComplete();
200 void OnIOComplete(int result
);
201 int RunLoop(int result
);
202 int DoLoop(int result
);
205 // Each of these methods corresponds to a State value. Those with an input
206 // argument receive the result from the previous state. If a method returns
207 // ERR_IO_PENDING, then the result from OnIOComplete will be passed to the
208 // next state method as the result arg.
210 int DoResolveProxy();
211 int DoResolveProxyComplete(int result
);
213 int DoWaitForJobComplete(int result
);
214 int DoInitConnection();
215 int DoInitConnectionComplete(int result
);
216 int DoWaitingUserAction(int result
);
217 int DoCreateStream();
218 int DoCreateStreamComplete(int result
);
219 int DoRestartTunnelAuth();
220 int DoRestartTunnelAuthComplete(int result
);
222 // Creates a SpdyHttpStream from the given values and sets to |stream_|. Does
223 // nothing if |stream_factory_| is for WebSockets.
224 int SetSpdyHttpStream(base::WeakPtr
<SpdySession
> session
, bool direct
);
226 // Returns to STATE_INIT_CONNECTION and resets some state.
227 void ReturnToStateInitConnection(bool close_connection
);
229 // Set the motivation for this request onto the underlying socket.
230 void SetSocketMotivation();
232 bool IsHttpsProxyAndHttpUrl() const;
234 // Returns true iff this Job is an alternate, that is, iff MarkAsAlternate has
236 bool IsAlternate() const;
238 // Returns true if this Job is a SPDY alternate job.
239 bool IsSpdyAlternate() const;
241 // Sets several fields of |ssl_config| for |server| based on the proxy info
242 // and other factors.
243 void InitSSLConfig(const HostPortPair
& server
,
244 SSLConfig
* ssl_config
,
245 bool is_proxy
) const;
247 // Retrieve SSLInfo from our SSL Socket.
248 // This must only be called when we are using an SSLSocket.
249 // After calling, the caller can use ssl_info_.
252 SpdySessionKey
GetSpdySessionKey() const;
254 // Returns true if the current request can use an existing spdy session.
255 bool CanUseExistingSpdySession() const;
257 // Called when we encounter a network error that could be resolved by trying
258 // a new proxy configuration. If there is another proxy configuration to try
259 // then this method sets next_state_ appropriately and returns either OK or
260 // ERR_IO_PENDING depending on whether or not the new proxy configuration is
261 // available synchronously or asynchronously. Otherwise, the given error
262 // code is simply returned.
263 int ReconsiderProxyAfterError(int error
);
265 // Called to handle a certificate error. Stores the certificate in the
266 // allowed_bad_certs list, and checks if the error can be ignored. Returns
267 // OK if it can be ignored, or the error code otherwise.
268 int HandleCertificateError(int error
);
270 // Called to handle a client certificate request.
271 int HandleCertificateRequest(int error
);
273 // Moves this stream request into SPDY mode.
274 void SwitchToSpdyMode();
276 // Should we force QUIC for this stream request.
277 bool ShouldForceQuic() const;
279 void MaybeMarkAlternativeServiceBroken();
281 ClientSocketPoolManager::SocketGroupType
GetSocketGroup() const;
283 void MaybeCopyConnectionAttemptsFromSocketOrHandle();
285 // Record histograms of latency until Connect() completes.
286 static void LogHttpConnectedMetrics(const ClientSocketHandle
& handle
);
288 // Invoked by the transport socket pool after host resolution is complete
289 // to allow the connection to be aborted, if a matching SPDY session can
290 // be found. Will return ERR_SPDY_SESSION_ALREADY_EXISTS if such a
291 // session is found, and OK otherwise.
292 static int OnHostResolution(SpdySessionPool
* spdy_session_pool
,
293 const SpdySessionKey
& spdy_session_key
,
294 const AddressList
& addresses
,
295 const BoundNetLog
& net_log
);
299 const HttpRequestInfo request_info_
;
300 RequestPriority priority_
;
301 ProxyInfo proxy_info_
;
302 SSLConfig server_ssl_config_
;
303 SSLConfig proxy_ssl_config_
;
304 const BoundNetLog net_log_
;
306 CompletionCallback io_callback_
;
307 scoped_ptr
<ClientSocketHandle
> connection_
;
308 HttpNetworkSession
* const session_
;
309 HttpStreamFactoryImpl
* const stream_factory_
;
311 ProxyService::PacRequest
* pac_request_
;
314 // The server we are trying to reach, could be that of the origin or of the
315 // alternative service.
316 HostPortPair server_
;
318 // The origin url we're trying to reach. This url may be different from the
319 // original request when host mapping rules are set-up.
322 // AlternateProtocol for this job if this is an alternate job.
323 AlternativeService alternative_service_
;
325 // AlternateProtocol for the other job if this is not an alternate job.
326 AlternativeService other_job_alternative_service_
;
328 // This is the Job we're dependent on. It will notify us if/when it's OK to
332 // |waiting_job_| is a Job waiting to see if |this| can reuse a connection.
333 // If |this| is unable to do so, we'll notify |waiting_job_| that it's ok to
334 // proceed and then race the two Jobs.
337 // True if handling a HTTPS request, or using SPDY with SSL
340 // True if this network transaction is using SPDY instead of HTTP.
343 // True if this network transaction is using QUIC instead of HTTP.
345 QuicStreamRequest quic_request_
;
347 // True if this job used an existing QUIC session.
348 bool using_existing_quic_session_
;
350 // Force quic for a specific port.
351 int force_quic_port_
;
353 // The certificate error while using SPDY over SSL for insecure URLs.
354 int spdy_certificate_error_
;
356 scoped_refptr
<HttpAuthController
>
357 auth_controllers_
[HttpAuth::AUTH_NUM_TARGETS
];
359 // True when the tunnel is in the process of being established - we can't
360 // read from the socket until the tunnel is done.
361 bool establishing_tunnel_
;
363 scoped_ptr
<HttpStream
> stream_
;
364 scoped_ptr
<WebSocketHandshakeStreamBase
> websocket_stream_
;
366 // True if we negotiated NPN.
367 bool was_npn_negotiated_
;
369 // Protocol negotiated with the server.
370 NextProto protocol_negotiated_
;
372 // 0 if we're not preconnecting. Otherwise, the number of streams to
376 scoped_ptr
<ValidSpdySessionPool
> valid_spdy_session_pool_
;
378 // Initialized when we create a new SpdySession.
379 base::WeakPtr
<SpdySession
> new_spdy_session_
;
381 // Initialized when we have an existing SpdySession.
382 base::WeakPtr
<SpdySession
> existing_spdy_session_
;
384 // Only used if |new_spdy_session_| is non-NULL.
385 bool spdy_session_direct_
;
387 JobStatus job_status_
;
388 JobStatus other_job_status_
;
390 base::WeakPtrFactory
<Job
> ptr_factory_
;
392 DISALLOW_COPY_AND_ASSIGN(Job
);
397 #endif // NET_HTTP_HTTP_STREAM_FACTORY_IMPL_JOB_H_