Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / http / http_network_transaction.h
blobe92364282bf1bc7ef7529f8e6307007a930c5857
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_NETWORK_TRANSACTION_H_
6 #define NET_HTTP_HTTP_NETWORK_TRANSACTION_H_
8 #include <stdint.h>
10 #include <string>
12 #include "base/basictypes.h"
13 #include "base/gtest_prod_util.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/time/time.h"
17 #include "net/base/request_priority.h"
18 #include "net/http/http_auth.h"
19 #include "net/http/http_request_headers.h"
20 #include "net/http/http_response_info.h"
21 #include "net/http/http_stream_factory.h"
22 #include "net/http/http_transaction.h"
23 #include "net/log/net_log.h"
24 #include "net/proxy/proxy_service.h"
25 #include "net/socket/connection_attempts.h"
26 #include "net/ssl/ssl_config_service.h"
27 #include "net/ssl/ssl_failure_state.h"
28 #include "net/websockets/websocket_handshake_stream_base.h"
30 namespace net {
32 class ClientSocketHandle;
33 class HttpAuthController;
34 class HttpNetworkSession;
35 class HttpStream;
36 class HttpStreamRequest;
37 class IOBuffer;
38 class ProxyInfo;
39 class SpdySession;
40 struct HttpRequestInfo;
42 class NET_EXPORT_PRIVATE HttpNetworkTransaction
43 : public HttpTransaction,
44 public HttpStreamRequest::Delegate {
45 public:
46 HttpNetworkTransaction(RequestPriority priority,
47 HttpNetworkSession* session);
49 ~HttpNetworkTransaction() override;
51 // HttpTransaction methods:
52 int Start(const HttpRequestInfo* request_info,
53 const CompletionCallback& callback,
54 const BoundNetLog& net_log) override;
55 int RestartIgnoringLastError(const CompletionCallback& callback) override;
56 int RestartWithCertificate(X509Certificate* client_cert,
57 const CompletionCallback& callback) override;
58 int RestartWithAuth(const AuthCredentials& credentials,
59 const CompletionCallback& callback) override;
60 bool IsReadyToRestartForAuth() override;
62 int Read(IOBuffer* buf,
63 int buf_len,
64 const CompletionCallback& callback) override;
65 void StopCaching() override;
66 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const override;
67 int64 GetTotalReceivedBytes() const override;
68 int64_t GetTotalSentBytes() const override;
69 void DoneReading() override;
70 const HttpResponseInfo* GetResponseInfo() const override;
71 LoadState GetLoadState() const override;
72 UploadProgress GetUploadProgress() const override;
73 void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
74 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
75 void SetPriority(RequestPriority priority) override;
76 void SetWebSocketHandshakeStreamCreateHelper(
77 WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
78 void SetBeforeNetworkStartCallback(
79 const BeforeNetworkStartCallback& callback) override;
80 void SetBeforeProxyHeadersSentCallback(
81 const BeforeProxyHeadersSentCallback& callback) override;
82 int ResumeNetworkStart() override;
84 // HttpStreamRequest::Delegate methods:
85 void OnStreamReady(const SSLConfig& used_ssl_config,
86 const ProxyInfo& used_proxy_info,
87 HttpStream* stream) override;
88 void OnWebSocketHandshakeStreamReady(
89 const SSLConfig& used_ssl_config,
90 const ProxyInfo& used_proxy_info,
91 WebSocketHandshakeStreamBase* stream) override;
92 void OnStreamFailed(int status,
93 const SSLConfig& used_ssl_config,
94 SSLFailureState ssl_failure_state) override;
95 void OnCertificateError(int status,
96 const SSLConfig& used_ssl_config,
97 const SSLInfo& ssl_info) override;
98 void OnNeedsProxyAuth(const HttpResponseInfo& response_info,
99 const SSLConfig& used_ssl_config,
100 const ProxyInfo& used_proxy_info,
101 HttpAuthController* auth_controller) override;
102 void OnNeedsClientAuth(const SSLConfig& used_ssl_config,
103 SSLCertRequestInfo* cert_info) override;
104 void OnHttpsProxyTunnelResponse(const HttpResponseInfo& response_info,
105 const SSLConfig& used_ssl_config,
106 const ProxyInfo& used_proxy_info,
107 HttpStream* stream) override;
109 void GetConnectionAttempts(ConnectionAttempts* out) const override;
111 private:
112 friend class HttpNetworkTransactionSSLTest;
114 FRIEND_TEST_ALL_PREFIXES(HttpNetworkTransactionTest,
115 ResetStateForRestart);
116 FRIEND_TEST_ALL_PREFIXES(SpdyNetworkTransactionTest,
117 WindowUpdateReceived);
118 FRIEND_TEST_ALL_PREFIXES(SpdyNetworkTransactionTest,
119 WindowUpdateSent);
120 FRIEND_TEST_ALL_PREFIXES(SpdyNetworkTransactionTest,
121 WindowUpdateOverflow);
122 FRIEND_TEST_ALL_PREFIXES(SpdyNetworkTransactionTest,
123 FlowControlStallResume);
124 FRIEND_TEST_ALL_PREFIXES(SpdyNetworkTransactionTest,
125 FlowControlStallResumeAfterSettings);
126 FRIEND_TEST_ALL_PREFIXES(SpdyNetworkTransactionTest,
127 FlowControlNegativeSendWindowSize);
129 enum State {
130 STATE_NOTIFY_BEFORE_CREATE_STREAM,
131 STATE_CREATE_STREAM,
132 STATE_CREATE_STREAM_COMPLETE,
133 STATE_INIT_STREAM,
134 STATE_INIT_STREAM_COMPLETE,
135 STATE_GENERATE_PROXY_AUTH_TOKEN,
136 STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE,
137 STATE_GENERATE_SERVER_AUTH_TOKEN,
138 STATE_GENERATE_SERVER_AUTH_TOKEN_COMPLETE,
139 STATE_INIT_REQUEST_BODY,
140 STATE_INIT_REQUEST_BODY_COMPLETE,
141 STATE_BUILD_REQUEST,
142 STATE_BUILD_REQUEST_COMPLETE,
143 STATE_SEND_REQUEST,
144 STATE_SEND_REQUEST_COMPLETE,
145 STATE_READ_HEADERS,
146 STATE_READ_HEADERS_COMPLETE,
147 STATE_READ_BODY,
148 STATE_READ_BODY_COMPLETE,
149 STATE_DRAIN_BODY_FOR_AUTH_RESTART,
150 STATE_DRAIN_BODY_FOR_AUTH_RESTART_COMPLETE,
151 STATE_NONE
154 bool IsSecureRequest() const;
156 // Returns true if the request is using an HTTP(S) proxy without being
157 // tunneled via the CONNECT method.
158 bool UsingHttpProxyWithoutTunnel() const;
160 void DoCallback(int result);
161 void OnIOComplete(int result);
163 // Runs the state transition loop.
164 int DoLoop(int result);
166 // Each of these methods corresponds to a State value. Those with an input
167 // argument receive the result from the previous state. If a method returns
168 // ERR_IO_PENDING, then the result from OnIOComplete will be passed to the
169 // next state method as the result arg.
170 int DoNotifyBeforeCreateStream();
171 int DoCreateStream();
172 int DoCreateStreamComplete(int result);
173 int DoInitStream();
174 int DoInitStreamComplete(int result);
175 int DoGenerateProxyAuthToken();
176 int DoGenerateProxyAuthTokenComplete(int result);
177 int DoGenerateServerAuthToken();
178 int DoGenerateServerAuthTokenComplete(int result);
179 int DoInitRequestBody();
180 int DoInitRequestBodyComplete(int result);
181 int DoBuildRequest();
182 int DoBuildRequestComplete(int result);
183 int DoSendRequest();
184 int DoSendRequestComplete(int result);
185 int DoReadHeaders();
186 int DoReadHeadersComplete(int result);
187 int DoReadBody();
188 int DoReadBodyComplete(int result);
189 int DoDrainBodyForAuthRestart();
190 int DoDrainBodyForAuthRestartComplete(int result);
192 void BuildRequestHeaders(bool using_http_proxy_without_tunnel);
194 // Writes a log message to help debugging in the field when we block a proxy
195 // response to a CONNECT request.
196 void LogBlockedTunnelResponse(int response_code) const;
198 // Called to handle a client certificate request.
199 int HandleCertificateRequest(int error);
201 // Called wherever ERR_HTTP_1_1_REQUIRED or
202 // ERR_PROXY_HTTP_1_1_REQUIRED has to be handled.
203 int HandleHttp11Required(int error);
205 // Called to possibly handle a client authentication error.
206 void HandleClientAuthError(int error);
208 // Called to possibly recover from an SSL handshake error. Sets next_state_
209 // and returns OK if recovering from the error. Otherwise, the same error
210 // code is returned.
211 int HandleSSLHandshakeError(int error);
213 // Called to possibly recover from the given error. Sets next_state_ and
214 // returns OK if recovering from the error. Otherwise, the same error code
215 // is returned.
216 int HandleIOError(int error);
218 // Gets the response headers from the HttpStream.
219 HttpResponseHeaders* GetResponseHeaders() const;
221 // Called when the socket is unexpectedly closed. Returns true if the request
222 // should be resent in case of a socket reuse/close race.
223 bool ShouldResendRequest() const;
225 // Resets the connection and the request headers for resend. Called when
226 // ShouldResendRequest() is true.
227 void ResetConnectionAndRequestForResend();
229 // Sets up the state machine to restart the transaction with auth.
230 void PrepareForAuthRestart(HttpAuth::Target target);
232 // Called when we don't need to drain the response body or have drained it.
233 // Resets |connection_| unless |keep_alive| is true, then calls
234 // ResetStateForRestart. Sets |next_state_| appropriately.
235 void DidDrainBodyForAuthRestart(bool keep_alive);
237 // Resets the members of the transaction so it can be restarted.
238 void ResetStateForRestart();
240 // Resets the members of the transaction, except |stream_|, which needs
241 // to be maintained for multi-round auth.
242 void ResetStateForAuthRestart();
244 // Records metrics relating to SSL fallbacks.
245 void RecordSSLFallbackMetrics(int result);
247 // Returns true if we should try to add a Proxy-Authorization header
248 bool ShouldApplyProxyAuth() const;
250 // Returns true if we should try to add an Authorization header.
251 bool ShouldApplyServerAuth() const;
253 // Handles HTTP status code 401 or 407.
254 // HandleAuthChallenge() returns a network error code, or OK on success.
255 // May update |pending_auth_target_| or |response_.auth_challenge|.
256 int HandleAuthChallenge();
258 // Returns true if we have auth credentials for the given target.
259 bool HaveAuth(HttpAuth::Target target) const;
261 // Get the {scheme, host, path, port} for the authentication target
262 GURL AuthURL(HttpAuth::Target target) const;
264 // Returns true if this transaction is for a WebSocket handshake
265 bool ForWebSocketHandshake() const;
267 // Debug helper.
268 static std::string DescribeState(State state);
270 void SetStream(HttpStream* stream);
272 void CopyConnectionAttemptsFromStreamRequest();
274 scoped_refptr<HttpAuthController>
275 auth_controllers_[HttpAuth::AUTH_NUM_TARGETS];
277 // Whether this transaction is waiting for proxy auth, server auth, or is
278 // not waiting for any auth at all. |pending_auth_target_| is read and
279 // cleared by RestartWithAuth().
280 HttpAuth::Target pending_auth_target_;
282 CompletionCallback io_callback_;
283 CompletionCallback callback_;
285 HttpNetworkSession* session_;
287 BoundNetLog net_log_;
288 const HttpRequestInfo* request_;
289 RequestPriority priority_;
290 HttpResponseInfo response_;
292 // |proxy_info_| is the ProxyInfo used by the HttpStreamRequest.
293 ProxyInfo proxy_info_;
295 scoped_ptr<HttpStreamRequest> stream_request_;
296 scoped_ptr<HttpStream> stream_;
298 // True if we've validated the headers that the stream parser has returned.
299 bool headers_valid_;
301 SSLConfig server_ssl_config_;
302 SSLConfig proxy_ssl_config_;
303 // The SSLFailureState of the most recent failed stream.
304 SSLFailureState server_ssl_failure_state_;
305 // fallback_error_code contains the error code that caused the last TLS
306 // fallback. If the fallback connection results in
307 // ERR_SSL_INAPPROPRIATE_FALLBACK (i.e. the server indicated that the
308 // fallback should not have been needed) then we use this value to return the
309 // original error that triggered the fallback.
310 int fallback_error_code_;
311 // The SSLFailureState which caused the last TLS version fallback.
312 SSLFailureState fallback_failure_state_;
314 HttpRequestHeaders request_headers_;
316 // The size in bytes of the buffer we use to drain the response body that
317 // we want to throw away. The response body is typically a small error
318 // page just a few hundred bytes long.
319 static const int kDrainBodyBufferSize = 1024;
321 // User buffer and length passed to the Read method.
322 scoped_refptr<IOBuffer> read_buf_;
323 int read_buf_len_;
325 // Total number of bytes received on all destroyed HttpStreams for this
326 // transaction.
327 int64 total_received_bytes_;
329 // Total number of bytes sent on all destroyed HttpStreams for this
330 // transaction.
331 int64_t total_sent_bytes_;
333 // When the transaction started / finished sending the request, including
334 // the body, if present.
335 base::TimeTicks send_start_time_;
336 base::TimeTicks send_end_time_;
338 // The next state in the state machine.
339 State next_state_;
341 // True when the tunnel is in the process of being established - we can't
342 // read from the socket until the tunnel is done.
343 bool establishing_tunnel_;
345 // The helper object to use to create WebSocketHandshakeStreamBase
346 // objects. Only relevant when establishing a WebSocket connection.
347 WebSocketHandshakeStreamBase::CreateHelper*
348 websocket_handshake_stream_base_create_helper_;
350 BeforeNetworkStartCallback before_network_start_callback_;
351 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_;
353 ConnectionAttempts connection_attempts_;
355 DISALLOW_COPY_AND_ASSIGN(HttpNetworkTransaction);
358 } // namespace net
360 #endif // NET_HTTP_HTTP_NETWORK_TRANSACTION_H_