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