Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / net / http / http_stream_factory_impl_job.h
blob637e3b1dda5fbbe0bbe8ad0594a99917a75f4c96
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"
26 namespace net {
28 class ClientSocketHandle;
29 class HttpAuthController;
30 class HttpNetworkSession;
31 class HttpStream;
32 class SpdySessionPool;
33 class QuicHttpStream;
35 // An HttpStreamRequestImpl exists for each stream which is in progress of being
36 // created for the StreamFactory.
37 class HttpStreamFactoryImpl::Job {
38 public:
39 // Constructor for non-alternative Job.
40 Job(HttpStreamFactoryImpl* stream_factory,
41 HttpNetworkSession* session,
42 const HttpRequestInfo& request_info,
43 RequestPriority priority,
44 const SSLConfig& server_ssl_config,
45 const SSLConfig& proxy_ssl_config,
46 NetLog* net_log);
47 // Constructor for alternative Job.
48 Job(HttpStreamFactoryImpl* stream_factory,
49 HttpNetworkSession* session,
50 const HttpRequestInfo& request_info,
51 RequestPriority priority,
52 const SSLConfig& server_ssl_config,
53 const SSLConfig& proxy_ssl_config,
54 AlternativeService alternative_service,
55 NetLog* net_log);
56 ~Job();
58 // Start initiates the process of creating a new HttpStream. |request| will be
59 // notified upon completion if the Job has not been Orphan()'d.
60 void Start(Request* request);
62 // Preconnect will attempt to request |num_streams| sockets from the
63 // appropriate ClientSocketPool.
64 int Preconnect(int num_streams);
66 int RestartTunnelWithProxyAuth(const AuthCredentials& credentials);
67 LoadState GetLoadState() const;
69 // Tells |this| to wait for |job| to resume it.
70 void WaitFor(Job* job);
72 // Tells |this| that |job| has determined it still needs to continue
73 // connecting, so allow |this| to continue. If this is not called, then
74 // |request_| is expected to cancel |this| by deleting it.
75 void Resume(Job* job);
77 // Used to detach the Job from |request|.
78 void Orphan(const Request* request);
80 void SetPriority(RequestPriority priority);
82 RequestPriority priority() const { return priority_; }
83 bool was_npn_negotiated() const;
84 NextProto protocol_negotiated() const;
85 bool using_spdy() const;
86 const BoundNetLog& net_log() const { return net_log_; }
88 const SSLConfig& server_ssl_config() const;
89 const SSLConfig& proxy_ssl_config() const;
90 const ProxyInfo& proxy_info() const;
92 // Indicates whether or not this job is performing a preconnect.
93 bool IsPreconnecting() const;
95 // Indicates whether or not this Job has been orphaned by a Request.
96 bool IsOrphaned() const;
98 // Called to indicate that this job succeeded, and some other jobs
99 // will be orphaned.
100 void ReportJobSucceededForRequest();
102 // Marks that the other |job| has completed.
103 void MarkOtherJobComplete(const Job& job);
105 private:
106 enum State {
107 STATE_START,
108 STATE_RESOLVE_PROXY,
109 STATE_RESOLVE_PROXY_COMPLETE,
111 // Note that when Alternate-Protocol says we can connect to an alternate
112 // port using a different protocol, we have the choice of communicating over
113 // the original protocol, or speaking the alternate protocol (currently,
114 // only npn-spdy) over an alternate port. For a cold page load, the http
115 // connection that delivers the http response that has the
116 // Alternate-Protocol header will already be warm. So, blocking the next
117 // http request on establishing a new npn-spdy connection would incur extra
118 // latency. Even if the http connection was not reused, establishing a new
119 // http connection is typically faster than npn-spdy, since npn-spdy
120 // requires a SSL handshake. Therefore, we start both the http and the
121 // npn-spdy jobs in parallel. In order not to unnecessarily waste sockets,
122 // we have the http job block on the npn-spdy job after proxy resolution.
123 // The npn-spdy job will Resume() the http job if, in
124 // STATE_INIT_CONNECTION_COMPLETE, it detects an error or does not find an
125 // existing SpdySession. In that case, the http and npn-spdy jobs will race.
126 STATE_WAIT_FOR_JOB,
127 STATE_WAIT_FOR_JOB_COMPLETE,
129 STATE_INIT_CONNECTION,
130 STATE_INIT_CONNECTION_COMPLETE,
131 STATE_WAITING_USER_ACTION,
132 STATE_RESTART_TUNNEL_AUTH,
133 STATE_RESTART_TUNNEL_AUTH_COMPLETE,
134 STATE_CREATE_STREAM,
135 STATE_CREATE_STREAM_COMPLETE,
136 STATE_DRAIN_BODY_FOR_AUTH_RESTART,
137 STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE,
138 STATE_DONE,
139 STATE_NONE
142 enum JobStatus {
143 STATUS_RUNNING,
144 STATUS_FAILED,
145 STATUS_BROKEN,
146 STATUS_SUCCEEDED
149 // Wrapper class for SpdySessionPool methods to enforce certificate
150 // requirements for SpdySessions.
151 class ValidSpdySessionPool {
152 public:
153 ValidSpdySessionPool(SpdySessionPool* spdy_session_pool,
154 GURL& origin_url,
155 bool is_spdy_alternative);
157 // Returns OK if a SpdySession was not found (in which case |spdy_session|
158 // is set to nullptr), or if one was found (in which case |spdy_session| is
159 // set to it) and it has an associated SSL certificate with is valid for
160 // |origin_url_|, or if this requirement does not apply because the Job is
161 // not a SPDY alternative job. Returns the appropriate error code
162 // otherwise,
163 // in which case |spdy_session| should not be used.
164 int FindAvailableSession(const SpdySessionKey& key,
165 const BoundNetLog& net_log,
166 base::WeakPtr<SpdySession>* spdy_session);
168 // Creates a SpdySession and sets |spdy_session| to point to it. Returns OK
169 // if the associated SSL certificate is valid for |origin_url_|, or if this
170 // requirement does not apply because the Job is not a SPDY alternative job.
171 // Returns the appropriate error code otherwise, in which case
172 // |spdy_session| should not be used.
173 int CreateAvailableSessionFromSocket(
174 const SpdySessionKey& key,
175 scoped_ptr<ClientSocketHandle> connection,
176 const BoundNetLog& net_log,
177 int certificate_error_code,
178 bool is_secure,
179 base::WeakPtr<SpdySession>* spdy_session);
181 private:
182 // Returns OK if |spdy_session| has an associated SSL certificate with is
183 // valid for |origin_url_|, or if this requirement does not apply because
184 // the Job is not a SPDY alternative job, or if |spdy_session| is null.
185 // Returns appropriate error code otherwise.
186 int CheckAlternativeServiceValidityForOrigin(
187 base::WeakPtr<SpdySession> spdy_session);
189 SpdySessionPool* const spdy_session_pool_;
190 const GURL origin_url_;
191 const bool is_spdy_alternative_;
194 void OnStreamReadyCallback();
195 void OnWebSocketHandshakeStreamReadyCallback();
196 // This callback function is called when a new SPDY session is created.
197 void OnNewSpdySessionReadyCallback();
198 void OnStreamFailedCallback(int result);
199 void OnCertificateErrorCallback(int result, const SSLInfo& ssl_info);
200 void OnNeedsProxyAuthCallback(const HttpResponseInfo& response_info,
201 HttpAuthController* auth_controller);
202 void OnNeedsClientAuthCallback(SSLCertRequestInfo* cert_info);
203 void OnHttpsProxyTunnelResponseCallback(const HttpResponseInfo& response_info,
204 HttpStream* stream);
205 void OnPreconnectsComplete();
207 void OnIOComplete(int result);
208 int RunLoop(int result);
209 int DoLoop(int result);
210 int StartInternal();
212 // Each of these methods corresponds to a State value. Those with an input
213 // argument receive the result from the previous state. If a method returns
214 // ERR_IO_PENDING, then the result from OnIOComplete will be passed to the
215 // next state method as the result arg.
216 int DoStart();
217 int DoResolveProxy();
218 int DoResolveProxyComplete(int result);
219 int DoWaitForJob();
220 int DoWaitForJobComplete(int result);
221 int DoInitConnection();
222 int DoInitConnectionComplete(int result);
223 int DoWaitingUserAction(int result);
224 int DoCreateStream();
225 int DoCreateStreamComplete(int result);
226 int DoRestartTunnelAuth();
227 int DoRestartTunnelAuthComplete(int result);
229 // Creates a SpdyHttpStream from the given values and sets to |stream_|. Does
230 // nothing if |stream_factory_| is for WebSockets.
231 int SetSpdyHttpStream(base::WeakPtr<SpdySession> session, bool direct);
233 // Returns to STATE_INIT_CONNECTION and resets some state.
234 void ReturnToStateInitConnection(bool close_connection);
236 // Set the motivation for this request onto the underlying socket.
237 void SetSocketMotivation();
239 bool IsHttpsProxyAndHttpUrl() const;
241 // Is this a SPDY or QUIC alternative Job?
242 bool IsSpdyAlternative() const;
243 bool IsQuicAlternative() const;
245 // Sets several fields of |ssl_config| for |server| based on the proxy info
246 // and other factors.
247 void InitSSLConfig(const HostPortPair& server,
248 SSLConfig* ssl_config,
249 bool is_proxy) const;
251 // Retrieve SSLInfo from our SSL Socket.
252 // This must only be called when we are using an SSLSocket.
253 // After calling, the caller can use ssl_info_.
254 void GetSSLInfo();
256 SpdySessionKey GetSpdySessionKey() const;
258 // Returns true if the current request can use an existing spdy session.
259 bool CanUseExistingSpdySession() const;
261 // Called when we encounter a network error that could be resolved by trying
262 // a new proxy configuration. If there is another proxy configuration to try
263 // then this method sets next_state_ appropriately and returns either OK or
264 // ERR_IO_PENDING depending on whether or not the new proxy configuration is
265 // available synchronously or asynchronously. Otherwise, the given error
266 // code is simply returned.
267 int ReconsiderProxyAfterError(int error);
269 // Called to handle a certificate error. Stores the certificate in the
270 // allowed_bad_certs list, and checks if the error can be ignored. Returns
271 // OK if it can be ignored, or the error code otherwise.
272 int HandleCertificateError(int error);
274 // Called to handle a client certificate request.
275 int HandleCertificateRequest(int error);
277 // Moves this stream request into SPDY mode.
278 void SwitchToSpdyMode();
280 // Should we force QUIC for this stream request.
281 bool ShouldForceQuic() const;
283 void MaybeMarkAlternativeServiceBroken();
285 ClientSocketPoolManager::SocketGroupType GetSocketGroup() const;
287 void MaybeCopyConnectionAttemptsFromSocketOrHandle();
289 // Record histograms of latency until Connect() completes.
290 static void LogHttpConnectedMetrics(const ClientSocketHandle& handle);
292 // Invoked by the transport socket pool after host resolution is complete
293 // to allow the connection to be aborted, if a matching SPDY session can
294 // be found. Will return ERR_SPDY_SESSION_ALREADY_EXISTS if such a
295 // session is found, and OK otherwise.
296 static int OnHostResolution(SpdySessionPool* spdy_session_pool,
297 const SpdySessionKey& spdy_session_key,
298 const AddressList& addresses,
299 const BoundNetLog& net_log);
301 Request* request_;
303 const HttpRequestInfo request_info_;
304 RequestPriority priority_;
305 ProxyInfo proxy_info_;
306 SSLConfig server_ssl_config_;
307 SSLConfig proxy_ssl_config_;
308 const BoundNetLog net_log_;
310 CompletionCallback io_callback_;
311 scoped_ptr<ClientSocketHandle> connection_;
312 HttpNetworkSession* const session_;
313 HttpStreamFactoryImpl* const stream_factory_;
314 State next_state_;
315 ProxyService::PacRequest* pac_request_;
316 SSLInfo ssl_info_;
318 // The server we are trying to reach, could be that of the origin or of the
319 // alternative service.
320 HostPortPair server_;
322 // The origin url we're trying to reach. This url may be different from the
323 // original request when host mapping rules are set-up.
324 GURL origin_url_;
326 // AlternativeService for this Job if this is an alternative Job.
327 const AlternativeService alternative_service_;
329 // AlternativeService for the other Job if this is not an alternative Job.
330 AlternativeService other_job_alternative_service_;
332 // This is the Job we're dependent on. It will notify us if/when it's OK to
333 // proceed.
334 Job* blocking_job_;
336 // |waiting_job_| is a Job waiting to see if |this| can reuse a connection.
337 // If |this| is unable to do so, we'll notify |waiting_job_| that it's ok to
338 // proceed and then race the two Jobs.
339 Job* waiting_job_;
341 // True if handling a HTTPS request, or using SPDY with SSL
342 bool using_ssl_;
344 // True if this network transaction is using SPDY instead of HTTP.
345 bool using_spdy_;
347 // True if this network transaction is using QUIC instead of HTTP.
348 bool using_quic_;
349 QuicStreamRequest quic_request_;
351 // True if this job used an existing QUIC session.
352 bool using_existing_quic_session_;
354 // Force quic for a specific port.
355 int force_quic_port_;
357 // The certificate error while using SPDY over SSL for insecure URLs.
358 int spdy_certificate_error_;
360 scoped_refptr<HttpAuthController>
361 auth_controllers_[HttpAuth::AUTH_NUM_TARGETS];
363 // True when the tunnel is in the process of being established - we can't
364 // read from the socket until the tunnel is done.
365 bool establishing_tunnel_;
367 scoped_ptr<HttpStream> stream_;
368 scoped_ptr<WebSocketHandshakeStreamBase> websocket_stream_;
370 // True if we negotiated NPN.
371 bool was_npn_negotiated_;
373 // Protocol negotiated with the server.
374 NextProto protocol_negotiated_;
376 // 0 if we're not preconnecting. Otherwise, the number of streams to
377 // preconnect.
378 int num_streams_;
380 scoped_ptr<ValidSpdySessionPool> valid_spdy_session_pool_;
382 // Initialized when we create a new SpdySession.
383 base::WeakPtr<SpdySession> new_spdy_session_;
385 // Initialized when we have an existing SpdySession.
386 base::WeakPtr<SpdySession> existing_spdy_session_;
388 // Only used if |new_spdy_session_| is non-NULL.
389 bool spdy_session_direct_;
391 JobStatus job_status_;
392 JobStatus other_job_status_;
394 base::WeakPtrFactory<Job> ptr_factory_;
396 DISALLOW_COPY_AND_ASSIGN(Job);
399 } // namespace net
401 #endif // NET_HTTP_HTTP_STREAM_FACTORY_IMPL_JOB_H_