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 void OnStreamReadyCallback();
144 void OnWebSocketHandshakeStreamReadyCallback();
145 // This callback function is called when a new SPDY session is created.
146 void OnNewSpdySessionReadyCallback();
147 void OnStreamFailedCallback(int result
);
148 void OnCertificateErrorCallback(int result
, const SSLInfo
& ssl_info
);
149 void OnNeedsProxyAuthCallback(const HttpResponseInfo
& response_info
,
150 HttpAuthController
* auth_controller
);
151 void OnNeedsClientAuthCallback(SSLCertRequestInfo
* cert_info
);
152 void OnHttpsProxyTunnelResponseCallback(const HttpResponseInfo
& response_info
,
154 void OnPreconnectsComplete();
156 void OnIOComplete(int result
);
157 int RunLoop(int result
);
158 int DoLoop(int result
);
161 // Each of these methods corresponds to a State value. Those with an input
162 // argument receive the result from the previous state. If a method returns
163 // ERR_IO_PENDING, then the result from OnIOComplete will be passed to the
164 // next state method as the result arg.
166 int DoResolveProxy();
167 int DoResolveProxyComplete(int result
);
169 int DoWaitForJobComplete(int result
);
170 int DoInitConnection();
171 int DoInitConnectionComplete(int result
);
172 int DoWaitingUserAction(int result
);
173 int DoCreateStream();
174 int DoCreateStreamComplete(int result
);
175 int DoRestartTunnelAuth();
176 int DoRestartTunnelAuthComplete(int result
);
178 // Creates a SpdyHttpStream from the given values and sets to |stream_|. Does
179 // nothing if |stream_factory_| is for WebSockets.
180 int SetSpdyHttpStream(base::WeakPtr
<SpdySession
> session
, bool direct
);
182 // Returns to STATE_INIT_CONNECTION and resets some state.
183 void ReturnToStateInitConnection(bool close_connection
);
185 // Set the motivation for this request onto the underlying socket.
186 void SetSocketMotivation();
188 bool IsHttpsProxyAndHttpUrl() const;
190 // Returns true iff this Job is an alternate, that is, iff MarkAsAlternate has
192 bool IsAlternate() const;
194 // Returns true if this Job is a SPDY alternate job.
195 bool IsSpdyAlternate() const;
197 // Sets several fields of |ssl_config| for |server| based on the proxy info
198 // and other factors.
199 void InitSSLConfig(const HostPortPair
& server
,
200 SSLConfig
* ssl_config
,
201 bool is_proxy
) const;
203 // Retrieve SSLInfo from our SSL Socket.
204 // This must only be called when we are using an SSLSocket.
205 // After calling, the caller can use ssl_info_.
208 SpdySessionKey
GetSpdySessionKey() const;
210 // Returns true if the current request can use an existing spdy session.
211 bool CanUseExistingSpdySession() const;
213 // Called when we encounter a network error that could be resolved by trying
214 // a new proxy configuration. If there is another proxy configuration to try
215 // then this method sets next_state_ appropriately and returns either OK or
216 // ERR_IO_PENDING depending on whether or not the new proxy configuration is
217 // available synchronously or asynchronously. Otherwise, the given error
218 // code is simply returned.
219 int ReconsiderProxyAfterError(int error
);
221 // Called to handle a certificate error. Stores the certificate in the
222 // allowed_bad_certs list, and checks if the error can be ignored. Returns
223 // OK if it can be ignored, or the error code otherwise.
224 int HandleCertificateError(int error
);
226 // Called to handle a client certificate request.
227 int HandleCertificateRequest(int error
);
229 // Moves this stream request into SPDY mode.
230 void SwitchToSpdyMode();
232 // Should we force QUIC for this stream request.
233 bool ShouldForceQuic() const;
235 void MaybeMarkAlternativeServiceBroken();
237 ClientSocketPoolManager::SocketGroupType
GetSocketGroup() const;
239 // Record histograms of latency until Connect() completes.
240 static void LogHttpConnectedMetrics(const ClientSocketHandle
& handle
);
242 // Invoked by the transport socket pool after host resolution is complete
243 // to allow the connection to be aborted, if a matching SPDY session can
244 // be found. Will return ERR_SPDY_SESSION_ALREADY_EXISTS if such a
245 // session is found, and OK otherwise.
246 static int OnHostResolution(SpdySessionPool
* spdy_session_pool
,
247 const SpdySessionKey
& spdy_session_key
,
248 const AddressList
& addresses
,
249 const BoundNetLog
& net_log
);
253 const HttpRequestInfo request_info_
;
254 RequestPriority priority_
;
255 ProxyInfo proxy_info_
;
256 SSLConfig server_ssl_config_
;
257 SSLConfig proxy_ssl_config_
;
258 const BoundNetLog net_log_
;
260 CompletionCallback io_callback_
;
261 scoped_ptr
<ClientSocketHandle
> connection_
;
262 HttpNetworkSession
* const session_
;
263 HttpStreamFactoryImpl
* const stream_factory_
;
265 ProxyService::PacRequest
* pac_request_
;
268 // The server we are trying to reach, could be that of the origin or of the
269 // alternative service.
270 HostPortPair server_
;
272 // The origin url we're trying to reach. This url may be different from the
273 // original request when host mapping rules are set-up.
276 // AlternateProtocol for this job if this is an alternate job.
277 AlternativeService alternative_service_
;
279 // AlternateProtocol for the other job if this is not an alternate job.
280 AlternativeService other_job_alternative_service_
;
282 // This is the Job we're dependent on. It will notify us if/when it's OK to
286 // |waiting_job_| is a Job waiting to see if |this| can reuse a connection.
287 // If |this| is unable to do so, we'll notify |waiting_job_| that it's ok to
288 // proceed and then race the two Jobs.
291 // True if handling a HTTPS request, or using SPDY with SSL
294 // True if this network transaction is using SPDY instead of HTTP.
297 // True if this network transaction is using QUIC instead of HTTP.
299 QuicStreamRequest quic_request_
;
301 // True if this job used an existing QUIC session.
302 bool using_existing_quic_session_
;
304 // Force quic for a specific port.
305 int force_quic_port_
;
307 // The certificate error while using SPDY over SSL for insecure URLs.
308 int spdy_certificate_error_
;
310 scoped_refptr
<HttpAuthController
>
311 auth_controllers_
[HttpAuth::AUTH_NUM_TARGETS
];
313 // True when the tunnel is in the process of being established - we can't
314 // read from the socket until the tunnel is done.
315 bool establishing_tunnel_
;
317 scoped_ptr
<HttpStream
> stream_
;
318 scoped_ptr
<WebSocketHandshakeStreamBase
> websocket_stream_
;
320 // True if we negotiated NPN.
321 bool was_npn_negotiated_
;
323 // Protocol negotiated with the server.
324 NextProto protocol_negotiated_
;
326 // 0 if we're not preconnecting. Otherwise, the number of streams to
330 // Initialized when we create a new SpdySession.
331 base::WeakPtr
<SpdySession
> new_spdy_session_
;
333 // Initialized when we have an existing SpdySession.
334 base::WeakPtr
<SpdySession
> existing_spdy_session_
;
336 // Only used if |new_spdy_session_| is non-NULL.
337 bool spdy_session_direct_
;
339 JobStatus job_status_
;
340 JobStatus other_job_status_
;
342 base::WeakPtrFactory
<Job
> ptr_factory_
;
344 DISALLOW_COPY_AND_ASSIGN(Job
);
349 #endif // NET_HTTP_HTTP_STREAM_FACTORY_IMPL_JOB_H_