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 "base/time/time.h"
12 #include "net/base/completion_callback.h"
13 #include "net/base/request_priority.h"
14 #include "net/http/http_auth.h"
15 #include "net/http/http_auth_controller.h"
16 #include "net/http/http_request_info.h"
17 #include "net/http/http_stream_factory_impl.h"
18 #include "net/log/net_log.h"
19 #include "net/proxy/proxy_service.h"
20 #include "net/quic/quic_stream_factory.h"
21 #include "net/socket/client_socket_handle.h"
22 #include "net/socket/client_socket_pool_manager.h"
23 #include "net/socket/ssl_client_socket.h"
24 #include "net/spdy/spdy_session_key.h"
25 #include "net/ssl/ssl_config_service.h"
29 class ClientSocketHandle
;
30 class HttpAuthController
;
31 class HttpNetworkSession
;
33 class SpdySessionPool
;
36 // An HttpStreamRequestImpl exists for each stream which is in progress of being
37 // created for the StreamFactory.
38 class HttpStreamFactoryImpl::Job
{
40 // Constructor for non-alternative Job.
41 Job(HttpStreamFactoryImpl
* stream_factory
,
42 HttpNetworkSession
* session
,
43 const HttpRequestInfo
& request_info
,
44 RequestPriority priority
,
45 const SSLConfig
& server_ssl_config
,
46 const SSLConfig
& proxy_ssl_config
,
48 // Constructor for alternative Job.
49 Job(HttpStreamFactoryImpl
* stream_factory
,
50 HttpNetworkSession
* session
,
51 const HttpRequestInfo
& request_info
,
52 RequestPriority priority
,
53 const SSLConfig
& server_ssl_config
,
54 const SSLConfig
& proxy_ssl_config
,
55 AlternativeService alternative_service
,
59 // Start initiates the process of creating a new HttpStream. |request| will be
60 // notified upon completion if the Job has not been Orphan()'d.
61 void Start(Request
* request
);
63 // Preconnect will attempt to request |num_streams| sockets from the
64 // appropriate ClientSocketPool.
65 int Preconnect(int num_streams
);
67 int RestartTunnelWithProxyAuth(const AuthCredentials
& credentials
);
68 LoadState
GetLoadState() const;
70 // Tells |this| to wait for |job| to resume it.
71 void WaitFor(Job
* job
);
73 // Tells |this| that |job| has determined it still needs to continue
74 // connecting, so allow |this| to continue after the specified |delay|. If
75 // this is not called, then |request_| is expected to cancel |this| by
77 void Resume(Job
* job
, const base::TimeDelta
& delay
);
79 // Used to detach the Job from |request|.
80 void Orphan(const Request
* request
);
82 void SetPriority(RequestPriority priority
);
84 RequestPriority
priority() const { return priority_
; }
85 bool was_npn_negotiated() const;
86 NextProto
protocol_negotiated() const;
87 bool using_spdy() const;
88 const BoundNetLog
& net_log() const { return net_log_
; }
90 const SSLConfig
& server_ssl_config() const;
91 const SSLConfig
& proxy_ssl_config() const;
92 const ProxyInfo
& proxy_info() const;
94 // Indicates whether or not this job is performing a preconnect.
95 bool IsPreconnecting() const;
97 // Indicates whether or not this Job has been orphaned by a Request.
98 bool IsOrphaned() const;
100 // Called to indicate that this job succeeded, and some other jobs
102 void ReportJobSucceededForRequest();
104 // Marks that the other |job| has completed.
105 void MarkOtherJobComplete(const Job
& job
);
111 STATE_RESOLVE_PROXY_COMPLETE
,
113 // Note that when Alternate-Protocol says we can connect to an alternate
114 // port using a different protocol, we have the choice of communicating over
115 // the original protocol, or speaking the alternate protocol (currently,
116 // only npn-spdy) over an alternate port. For a cold page load, the http
117 // connection that delivers the http response that has the
118 // Alternate-Protocol header will already be warm. So, blocking the next
119 // http request on establishing a new npn-spdy connection would incur extra
120 // latency. Even if the http connection was not reused, establishing a new
121 // http connection is typically faster than npn-spdy, since npn-spdy
122 // requires a SSL handshake. Therefore, we start both the http and the
123 // npn-spdy jobs in parallel. In order not to unnecessarily waste sockets,
124 // we have the http job block on the npn-spdy job after proxy resolution.
125 // The npn-spdy job will Resume() the http job if, in
126 // STATE_INIT_CONNECTION_COMPLETE, it detects an error or does not find an
127 // existing SpdySession. In that case, the http and npn-spdy jobs will race.
129 STATE_WAIT_FOR_JOB_COMPLETE
,
131 STATE_INIT_CONNECTION
,
132 STATE_INIT_CONNECTION_COMPLETE
,
133 STATE_WAITING_USER_ACTION
,
134 STATE_RESTART_TUNNEL_AUTH
,
135 STATE_RESTART_TUNNEL_AUTH_COMPLETE
,
137 STATE_CREATE_STREAM_COMPLETE
,
138 STATE_DRAIN_BODY_FOR_AUTH_RESTART
,
139 STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE
,
151 // Wrapper class for SpdySessionPool methods to enforce certificate
152 // requirements for SpdySessions.
153 class ValidSpdySessionPool
{
155 ValidSpdySessionPool(SpdySessionPool
* spdy_session_pool
,
157 bool is_spdy_alternative
);
159 // Returns OK if a SpdySession was not found (in which case |spdy_session|
160 // is set to nullptr), or if one was found (in which case |spdy_session| is
161 // set to it) and it has an associated SSL certificate with is valid for
162 // |origin_url_|, or if this requirement does not apply because the Job is
163 // not a SPDY alternative job. Returns the appropriate error code
165 // in which case |spdy_session| should not be used.
166 int FindAvailableSession(const SpdySessionKey
& key
,
167 const BoundNetLog
& net_log
,
168 base::WeakPtr
<SpdySession
>* spdy_session
);
170 // Creates a SpdySession and sets |spdy_session| to point to it. Returns OK
171 // if the associated SSL certificate is valid for |origin_url_|, or if this
172 // requirement does not apply because the Job is not a SPDY alternative job.
173 // Returns the appropriate error code otherwise, in which case
174 // |spdy_session| should not be used.
175 int CreateAvailableSessionFromSocket(
176 const SpdySessionKey
& key
,
177 scoped_ptr
<ClientSocketHandle
> connection
,
178 const BoundNetLog
& net_log
,
179 int certificate_error_code
,
181 base::WeakPtr
<SpdySession
>* spdy_session
);
184 // Returns OK if |spdy_session| has an associated SSL certificate with is
185 // valid for |origin_url_|, or if this requirement does not apply because
186 // the Job is not a SPDY alternative job, or if |spdy_session| is null.
187 // Returns appropriate error code otherwise.
188 int CheckAlternativeServiceValidityForOrigin(
189 base::WeakPtr
<SpdySession
> spdy_session
);
191 SpdySessionPool
* const spdy_session_pool_
;
192 const GURL origin_url_
;
193 const bool is_spdy_alternative_
;
196 void OnStreamReadyCallback();
197 void OnWebSocketHandshakeStreamReadyCallback();
198 // This callback function is called when a new SPDY session is created.
199 void OnNewSpdySessionReadyCallback();
200 void OnStreamFailedCallback(int result
);
201 void OnCertificateErrorCallback(int result
, const SSLInfo
& ssl_info
);
202 void OnNeedsProxyAuthCallback(const HttpResponseInfo
& response_info
,
203 HttpAuthController
* auth_controller
);
204 void OnNeedsClientAuthCallback(SSLCertRequestInfo
* cert_info
);
205 void OnHttpsProxyTunnelResponseCallback(const HttpResponseInfo
& response_info
,
207 void OnPreconnectsComplete();
209 void OnIOComplete(int result
);
210 int RunLoop(int result
);
211 int DoLoop(int result
);
214 // Each of these methods corresponds to a State value. Those with an input
215 // argument receive the result from the previous state. If a method returns
216 // ERR_IO_PENDING, then the result from OnIOComplete will be passed to the
217 // next state method as the result arg.
219 int DoResolveProxy();
220 int DoResolveProxyComplete(int result
);
222 int DoWaitForJobComplete(int result
);
223 int DoInitConnection();
224 int DoInitConnectionComplete(int result
);
225 int DoWaitingUserAction(int result
);
226 int DoCreateStream();
227 int DoCreateStreamComplete(int result
);
228 int DoRestartTunnelAuth();
229 int DoRestartTunnelAuthComplete(int result
);
231 // Creates a SpdyHttpStream from the given values and sets to |stream_|. Does
232 // nothing if |stream_factory_| is for WebSockets.
233 int SetSpdyHttpStream(base::WeakPtr
<SpdySession
> session
, bool direct
);
235 // Returns to STATE_INIT_CONNECTION and resets some state.
236 void ReturnToStateInitConnection(bool close_connection
);
238 // Set the motivation for this request onto the underlying socket.
239 void SetSocketMotivation();
241 bool IsHttpsProxyAndHttpUrl() const;
243 // Is this a SPDY or QUIC alternative Job?
244 bool IsSpdyAlternative() const;
245 bool IsQuicAlternative() const;
247 // Sets several fields of |ssl_config| for |server| based on the proxy info
248 // and other factors.
249 void InitSSLConfig(const HostPortPair
& server
,
250 SSLConfig
* ssl_config
,
251 bool is_proxy
) const;
253 // Retrieve SSLInfo from our SSL Socket.
254 // This must only be called when we are using an SSLSocket.
255 // After calling, the caller can use ssl_info_.
258 SpdySessionKey
GetSpdySessionKey() const;
260 // Returns true if the current request can use an existing spdy session.
261 bool CanUseExistingSpdySession() const;
263 // Called when we encounter a network error that could be resolved by trying
264 // a new proxy configuration. If there is another proxy configuration to try
265 // then this method sets next_state_ appropriately and returns either OK or
266 // ERR_IO_PENDING depending on whether or not the new proxy configuration is
267 // available synchronously or asynchronously. Otherwise, the given error
268 // code is simply returned.
269 int ReconsiderProxyAfterError(int error
);
271 // Called to handle a certificate error. Stores the certificate in the
272 // allowed_bad_certs list, and checks if the error can be ignored. Returns
273 // OK if it can be ignored, or the error code otherwise.
274 int HandleCertificateError(int error
);
276 // Called to handle a client certificate request.
277 int HandleCertificateRequest(int error
);
279 // Moves this stream request into SPDY mode.
280 void SwitchToSpdyMode();
282 // Should we force QUIC for this stream request.
283 bool ShouldForceQuic() const;
285 void MaybeMarkAlternativeServiceBroken();
287 ClientSocketPoolManager::SocketGroupType
GetSocketGroup() const;
289 void MaybeCopyConnectionAttemptsFromSocketOrHandle();
291 // Record histograms of latency until Connect() completes.
292 static void LogHttpConnectedMetrics(const ClientSocketHandle
& handle
);
294 // Invoked by the transport socket pool after host resolution is complete
295 // to allow the connection to be aborted, if a matching SPDY session can
296 // be found. Will return ERR_SPDY_SESSION_ALREADY_EXISTS if such a
297 // session is found, and OK otherwise.
298 static int OnHostResolution(SpdySessionPool
* spdy_session_pool
,
299 const SpdySessionKey
& spdy_session_key
,
300 const AddressList
& addresses
,
301 const BoundNetLog
& net_log
);
305 const HttpRequestInfo request_info_
;
306 RequestPriority priority_
;
307 ProxyInfo proxy_info_
;
308 SSLConfig server_ssl_config_
;
309 SSLConfig proxy_ssl_config_
;
310 const BoundNetLog net_log_
;
312 CompletionCallback io_callback_
;
313 scoped_ptr
<ClientSocketHandle
> connection_
;
314 HttpNetworkSession
* const session_
;
315 HttpStreamFactoryImpl
* const stream_factory_
;
317 ProxyService::PacRequest
* pac_request_
;
320 // The server we are trying to reach, could be that of the origin or of the
321 // alternative service.
322 HostPortPair server_
;
324 // The origin url we're trying to reach. This url may be different from the
325 // original request when host mapping rules are set-up.
328 // AlternativeService for this Job if this is an alternative Job.
329 const AlternativeService alternative_service_
;
331 // AlternativeService for the other Job if this is not an alternative Job.
332 AlternativeService other_job_alternative_service_
;
334 // This is the Job we're dependent on. It will notify us if/when it's OK to
338 // |waiting_job_| is a Job waiting to see if |this| can reuse a connection.
339 // If |this| is unable to do so, we'll notify |waiting_job_| that it's ok to
340 // proceed and then race the two Jobs.
343 // True if handling a HTTPS request, or using SPDY with SSL
346 // True if this network transaction is using SPDY instead of HTTP.
349 // True if this network transaction is using QUIC instead of HTTP.
351 QuicStreamRequest quic_request_
;
353 // True if this job used an existing QUIC session.
354 bool using_existing_quic_session_
;
356 // Force quic for a specific port.
357 int force_quic_port_
;
359 // The certificate error while using SPDY over SSL for insecure URLs.
360 int spdy_certificate_error_
;
362 scoped_refptr
<HttpAuthController
>
363 auth_controllers_
[HttpAuth::AUTH_NUM_TARGETS
];
365 // True when the tunnel is in the process of being established - we can't
366 // read from the socket until the tunnel is done.
367 bool establishing_tunnel_
;
369 scoped_ptr
<HttpStream
> stream_
;
370 scoped_ptr
<WebSocketHandshakeStreamBase
> websocket_stream_
;
372 // True if we negotiated NPN.
373 bool was_npn_negotiated_
;
375 // Protocol negotiated with the server.
376 NextProto protocol_negotiated_
;
378 // 0 if we're not preconnecting. Otherwise, the number of streams to
382 scoped_ptr
<ValidSpdySessionPool
> valid_spdy_session_pool_
;
384 // Initialized when we create a new SpdySession.
385 base::WeakPtr
<SpdySession
> new_spdy_session_
;
387 // Initialized when we have an existing SpdySession.
388 base::WeakPtr
<SpdySession
> existing_spdy_session_
;
390 // Only used if |new_spdy_session_| is non-NULL.
391 bool spdy_session_direct_
;
393 JobStatus job_status_
;
394 JobStatus other_job_status_
;
396 base::WeakPtrFactory
<Job
> ptr_factory_
;
398 DISALLOW_COPY_AND_ASSIGN(Job
);
403 #endif // NET_HTTP_HTTP_STREAM_FACTORY_IMPL_JOB_H_