Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / http / http_network_transaction.h
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.
4
5 #ifndef NET_HTTP_HTTP_NETWORK_TRANSACTION_H_
6 #define NET_HTTP_HTTP_NETWORK_TRANSACTION_H_
7
8 #include <string>
9
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"
25
26 namespace net {
27
28 class ClientSocketHandle;
29 class HttpAuthController;
30 class HttpNetworkSession;
31 class HttpStream;
32 class HttpStreamRequest;
33 class IOBuffer;
34 class ProxyInfo;
35 class SpdySession;
36 struct HttpRequestInfo;
37
38 class NET_EXPORT_PRIVATE HttpNetworkTransaction
39     : public HttpTransaction,
40       public HttpStreamRequest::Delegate {
41  public:
42   HttpNetworkTransaction(RequestPriority priority,
43                          HttpNetworkSession* session);
44
45   ~HttpNetworkTransaction() override;
46
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;
57
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;
78
79   // HttpStreamRequest::Delegate methods:
80   void OnStreamReady(const SSLConfig& used_ssl_config,
81                      const ProxyInfo& used_proxy_info,
82                      HttpStream* 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                                   HttpStream* stream) override;
101
102  private:
103   friend class HttpNetworkTransactionSSLTest;
104
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);
119
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
143   };
144
145   bool is_https_request() const;
146
147   void DoCallback(int result);
148   void OnIOComplete(int result);
149
150   // Runs the state transition loop.
151   int DoLoop(int result);
152
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);
178
179   void BuildRequestHeaders(bool using_proxy);
180
181   // Writes a log message to help debugging in the field when we block a proxy
182   // response to a CONNECT request.
183   void LogBlockedTunnelResponse(int response_code) const;
184
185   // Called to handle a client certificate request.
186   int HandleCertificateRequest(int error);
187
188   // Called to possibly handle a client authentication error.
189   void HandleClientAuthError(int error);
190
191   // Called to possibly recover from an SSL handshake error.  Sets next_state_
192   // and returns OK if recovering from the error.  Otherwise, the same error
193   // code is returned.
194   int HandleSSLHandshakeError(int error);
195
196   // Called to possibly recover from the given error.  Sets next_state_ and
197   // returns OK if recovering from the error.  Otherwise, the same error code
198   // is returned.
199   int HandleIOError(int error);
200
201   // Gets the response headers from the HttpStream.
202   HttpResponseHeaders* GetResponseHeaders() const;
203
204   // Called when the socket is unexpectedly closed.  Returns true if the request
205   // should be resent in case of a socket reuse/close race.
206   bool ShouldResendRequest() const;
207
208   // Resets the connection and the request headers for resend.  Called when
209   // ShouldResendRequest() is true.
210   void ResetConnectionAndRequestForResend();
211
212   // Sets up the state machine to restart the transaction with auth.
213   void PrepareForAuthRestart(HttpAuth::Target target);
214
215   // Called when we don't need to drain the response body or have drained it.
216   // Resets |connection_| unless |keep_alive| is true, then calls
217   // ResetStateForRestart.  Sets |next_state_| appropriately.
218   void DidDrainBodyForAuthRestart(bool keep_alive);
219
220   // Resets the members of the transaction so it can be restarted.
221   void ResetStateForRestart();
222
223   // Resets the members of the transaction, except |stream_|, which needs
224   // to be maintained for multi-round auth.
225   void ResetStateForAuthRestart();
226
227   // Returns true if we should try to add a Proxy-Authorization header
228   bool ShouldApplyProxyAuth() const;
229
230   // Returns true if we should try to add an Authorization header.
231   bool ShouldApplyServerAuth() const;
232
233   // Handles HTTP status code 401 or 407.
234   // HandleAuthChallenge() returns a network error code, or OK on success.
235   // May update |pending_auth_target_| or |response_.auth_challenge|.
236   int HandleAuthChallenge();
237
238   // Returns true if we have auth credentials for the given target.
239   bool HaveAuth(HttpAuth::Target target) const;
240
241   // Get the {scheme, host, path, port} for the authentication target
242   GURL AuthURL(HttpAuth::Target target) const;
243
244   // Returns true if this transaction is for a WebSocket handshake
245   bool ForWebSocketHandshake() const;
246
247   // Debug helper.
248   static std::string DescribeState(State state);
249
250   void SetStream(HttpStream* stream);
251
252   scoped_refptr<HttpAuthController>
253       auth_controllers_[HttpAuth::AUTH_NUM_TARGETS];
254
255   // Whether this transaction is waiting for proxy auth, server auth, or is
256   // not waiting for any auth at all. |pending_auth_target_| is read and
257   // cleared by RestartWithAuth().
258   HttpAuth::Target pending_auth_target_;
259
260   CompletionCallback io_callback_;
261   CompletionCallback callback_;
262
263   HttpNetworkSession* session_;
264
265   BoundNetLog net_log_;
266   const HttpRequestInfo* request_;
267   RequestPriority priority_;
268   HttpResponseInfo response_;
269
270   // |proxy_info_| is the ProxyInfo used by the HttpStreamRequest.
271   ProxyInfo proxy_info_;
272
273   scoped_ptr<HttpStreamRequest> stream_request_;
274   scoped_ptr<HttpStream> stream_;
275
276   // True if we've validated the headers that the stream parser has returned.
277   bool headers_valid_;
278
279   SSLConfig server_ssl_config_;
280   SSLConfig proxy_ssl_config_;
281   // fallback_error_code contains the error code that caused the last TLS
282   // fallback. If the fallback connection results in
283   // ERR_SSL_INAPPROPRIATE_FALLBACK (i.e. the server indicated that the
284   // fallback should not have been needed) then we use this value to return the
285   // original error that triggered the fallback.
286   int fallback_error_code_;
287
288   HttpRequestHeaders request_headers_;
289
290   // The size in bytes of the buffer we use to drain the response body that
291   // we want to throw away.  The response body is typically a small error
292   // page just a few hundred bytes long.
293   static const int kDrainBodyBufferSize = 1024;
294
295   // User buffer and length passed to the Read method.
296   scoped_refptr<IOBuffer> read_buf_;
297   int read_buf_len_;
298
299   // Total number of bytes received on streams for this transaction.
300   int64 total_received_bytes_;
301
302   // When the transaction started / finished sending the request, including
303   // the body, if present.
304   base::TimeTicks send_start_time_;
305   base::TimeTicks send_end_time_;
306
307   // The next state in the state machine.
308   State next_state_;
309
310   // True when the tunnel is in the process of being established - we can't
311   // read from the socket until the tunnel is done.
312   bool establishing_tunnel_;
313
314   // The helper object to use to create WebSocketHandshakeStreamBase
315   // objects. Only relevant when establishing a WebSocket connection.
316   WebSocketHandshakeStreamBase::CreateHelper*
317       websocket_handshake_stream_base_create_helper_;
318
319   BeforeNetworkStartCallback before_network_start_callback_;
320   BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_;
321
322   DISALLOW_COPY_AND_ASSIGN(HttpNetworkTransaction);
323 };
324
325 }  // namespace net
326
327 #endif  // NET_HTTP_HTTP_NETWORK_TRANSACTION_H_