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