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_SOCKET_STREAM_SOCKET_STREAM_H_
6#define NET_SOCKET_STREAM_SOCKET_STREAM_H_
7
8#include <deque>
9#include <map>
10#include <string>
11
12#include "base/memory/linked_ptr.h"
13#include "base/memory/ref_counted.h"
14#include "base/memory/scoped_ptr.h"
15#include "net/base/address_list.h"
16#include "net/base/completion_callback.h"
17#include "net/base/io_buffer.h"
18#include "net/base/net_errors.h"
19#include "net/base/net_export.h"
20#include "net/base/net_log.h"
21#include "net/base/privacy_mode.h"
22#include "net/proxy/proxy_service.h"
23#include "net/ssl/ssl_config_service.h"
24#include "net/url_request/url_request.h"
25
26namespace net {
27
28class AuthChallengeInfo;
29class CertVerifier;
30class ClientSocketFactory;
31class ClientSocketHandle;
32class CookieOptions;
33class HostResolver;
34class HttpAuthController;
35class SSLInfo;
36class ServerBoundCertService;
37class SingleRequestHostResolver;
38class SocketStreamMetrics;
39class TransportSecurityState;
40class URLRequestContext;
41
42// SocketStream is used to implement Web Sockets.
43// It provides plain full-duplex stream with proxy and SSL support.
44// For proxy authentication, only basic mechanisum is supported.  It will try
45// authentication identity for proxy URL first.  If server requires proxy
46// authentication, it will try authentication identity for realm that server
47// requests.
48class NET_EXPORT SocketStream
49    : public base::RefCountedThreadSafe<SocketStream> {
50 public:
51  // Derive from this class and add your own data members to associate extra
52  // information with a SocketStream.  Use GetUserData(key) and
53  // SetUserData(key, data).
54  class UserData {
55   public:
56    UserData() {}
57    virtual ~UserData() {}
58  };
59
60  class NET_EXPORT Delegate {
61   public:
62    virtual int OnStartOpenConnection(SocketStream* socket,
63                                      const CompletionCallback& callback);
64
65    // Called when a socket stream has been connected.  The socket stream is
66    // allowed to buffer pending send data at most |max_pending_send_allowed|
67    // bytes.  A client of the socket stream should keep track of how much
68    // pending send data it has and must not call SendData() if the pending
69    // data goes over |max_pending_send_allowed| bytes.
70    virtual void OnConnected(SocketStream* socket,
71                             int max_pending_send_allowed) = 0;
72
73    // Called when |amount_sent| bytes of data are sent.
74    virtual void OnSentData(SocketStream* socket,
75                            int amount_sent) = 0;
76
77    // Called when |len| bytes of |data| are received.
78    virtual void OnReceivedData(SocketStream* socket,
79                                const char* data, int len) = 0;
80
81    // Called when the socket stream has been closed.
82    virtual void OnClose(SocketStream* socket) = 0;
83
84    // Called when proxy authentication required.
85    // The delegate should call RestartWithAuth() if credential for |auth_info|
86    // is found in password database, or call Close() to close the connection.
87    virtual void OnAuthRequired(SocketStream* socket,
88                                AuthChallengeInfo* auth_info);
89
90    // Called when using SSL and the server responds with a certificate with an
91    // error. The delegate should call CancelBecauseOfCertError() or
92    // ContinueDespiteCertError() to resume connection handling.
93    virtual void OnSSLCertificateError(SocketStream* socket,
94                                       const SSLInfo& ssl_info,
95                                       bool fatal);
96
97    // Called when an error occured.
98    // This is only for error reporting to the delegate.
99    // |error| is net::Error.
100    virtual void OnError(const SocketStream* socket, int error) {}
101
102    // Called when reading cookies to allow the delegate to block access to the
103    // cookie.
104    virtual bool CanGetCookies(SocketStream* socket, const GURL& url);
105
106    // Called when a cookie is set to allow the delegate to block access to the
107    // cookie.
108    virtual bool CanSetCookie(SocketStream* request,
109                              const GURL& url,
110                              const std::string& cookie_line,
111                              CookieOptions* options);
112
113   protected:
114    virtual ~Delegate() {}
115  };
116
117  SocketStream(const GURL& url, Delegate* delegate);
118
119  // The user data allows the clients to associate data with this job.
120  // Multiple user data values can be stored under different keys.
121  // This job will TAKE OWNERSHIP of the given data pointer, and will
122  // delete the object if it is changed or the job is destroyed.
123  UserData* GetUserData(const void* key) const;
124  void SetUserData(const void* key, UserData* data);
125
126  const GURL& url() const { return url_; }
127  bool is_secure() const;
128  const AddressList& address_list() const { return addresses_; }
129  Delegate* delegate() const { return delegate_; }
130  int max_pending_send_allowed() const { return max_pending_send_allowed_; }
131
132  URLRequestContext* context() { return context_; }
133  // There're some asynchronous operations and members that are constructed from
134  // |context|. Be careful when you use this for the second time or more.
135  void set_context(URLRequestContext* context);
136
137  const SSLConfig& server_ssl_config() const { return server_ssl_config_; }
138  PrivacyMode privacy_mode() const { return privacy_mode_; }
139  void CheckPrivacyMode();
140
141  BoundNetLog* net_log() { return &net_log_; }
142
143  // Opens the connection on the IO thread.
144  // Once the connection is established, calls delegate's OnConnected.
145  virtual void Connect();
146
147  // Buffers |data| of |len| bytes for send and returns true if successful.
148  // If size of buffered data exceeds |max_pending_send_allowed_|, sends no
149  // data and returns false. |len| must be positive.
150  virtual bool SendData(const char* data, int len);
151
152  // Requests to close the connection.
153  // Once the connection is closed, calls delegate's OnClose.
154  virtual void Close();
155
156  // Restarts with authentication info.
157  // Should be used for response of OnAuthRequired.
158  virtual void RestartWithAuth(const AuthCredentials& credentials);
159
160  // Detach delegate.  Call before delegate is deleted.
161  // Once delegate is detached, close the socket stream and never call delegate
162  // back.
163  virtual void DetachDelegate();
164
165  const ProxyServer& proxy_server() const;
166
167  // Sets an alternative ClientSocketFactory.  Doesn't take ownership of
168  // |factory|.  For testing purposes only.
169  void SetClientSocketFactory(ClientSocketFactory* factory);
170
171  // Cancels the connection because of an error.
172  // |error| is net::Error which represents the error.
173  void CancelWithError(int error);
174
175  // Cancels the connection because of receiving a certificate with an error.
176  void CancelWithSSLError(const SSLInfo& ssl_info);
177
178  // Continues to establish the connection in spite of an error. Usually this
179  // case happens because users allow certificate with an error by manual
180  // actions on alert dialog or browser cached such kinds of user actions.
181  void ContinueDespiteError();
182
183 protected:
184  friend class base::RefCountedThreadSafe<SocketStream>;
185  virtual ~SocketStream();
186
187  Delegate* delegate_;
188
189 private:
190  FRIEND_TEST_ALL_PREFIXES(SocketStreamTest, IOPending);
191  FRIEND_TEST_ALL_PREFIXES(SocketStreamTest, SwitchAfterPending);
192  FRIEND_TEST_ALL_PREFIXES(SocketStreamTest,
193                           NullContextSocketStreamShouldNotCrash);
194
195  friend class WebSocketThrottleTest;
196
197  typedef std::map<const void*, linked_ptr<UserData> > UserDataMap;
198  typedef std::deque< scoped_refptr<IOBufferWithSize> > PendingDataQueue;
199
200  class RequestHeaders : public IOBuffer {
201   public:
202    RequestHeaders() : IOBuffer() {}
203
204    void SetDataOffset(size_t offset) {
205      data_ = const_cast<char*>(headers_.data()) + offset;
206    }
207
208    std::string headers_;
209
210    private:
211     virtual ~RequestHeaders();
212  };
213
214  class ResponseHeaders : public IOBuffer {
215   public:
216    ResponseHeaders();
217
218    void SetDataOffset(size_t offset) { data_ = headers_.get() + offset; }
219    char* headers() const { return headers_.get(); }
220    void Reset() { headers_.reset(); }
221    void Realloc(size_t new_size);
222
223   private:
224     virtual ~ResponseHeaders();
225
226    scoped_ptr_malloc<char> headers_;
227  };
228
229  enum State {
230    STATE_NONE,
231    STATE_BEFORE_CONNECT,
232    STATE_BEFORE_CONNECT_COMPLETE,
233    STATE_RESOLVE_PROXY,
234    STATE_RESOLVE_PROXY_COMPLETE,
235    STATE_RESOLVE_HOST,
236    STATE_RESOLVE_HOST_COMPLETE,
237    STATE_RESOLVE_PROTOCOL,
238    STATE_RESOLVE_PROTOCOL_COMPLETE,
239    STATE_TCP_CONNECT,
240    STATE_TCP_CONNECT_COMPLETE,
241    STATE_GENERATE_PROXY_AUTH_TOKEN,
242    STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE,
243    STATE_WRITE_TUNNEL_HEADERS,
244    STATE_WRITE_TUNNEL_HEADERS_COMPLETE,
245    STATE_READ_TUNNEL_HEADERS,
246    STATE_READ_TUNNEL_HEADERS_COMPLETE,
247    STATE_SOCKS_CONNECT,
248    STATE_SOCKS_CONNECT_COMPLETE,
249    STATE_SECURE_PROXY_CONNECT,
250    STATE_SECURE_PROXY_CONNECT_COMPLETE,
251    STATE_SECURE_PROXY_HANDLE_CERT_ERROR,
252    STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE,
253    STATE_SSL_CONNECT,
254    STATE_SSL_CONNECT_COMPLETE,
255    STATE_SSL_HANDLE_CERT_ERROR,
256    STATE_SSL_HANDLE_CERT_ERROR_COMPLETE,
257    STATE_READ_WRITE,
258    STATE_AUTH_REQUIRED,
259    STATE_CLOSE,
260  };
261
262  enum ProxyMode {
263    kDirectConnection,  // If using a direct connection
264    kTunnelProxy,  // If using a tunnel (CONNECT method as HTTPS)
265    kSOCKSProxy,  // If using a SOCKS proxy
266  };
267
268  // Use the same number as HttpNetworkTransaction::kMaxHeaderBufSize.
269  enum { kMaxTunnelResponseHeadersSize = 32768 };  // 32 kilobytes.
270
271  // Used for WebSocketThrottleTest.
272  void set_addresses(const AddressList& addresses);
273
274  void DoClose();
275
276  // Finishes the job.
277  // Calls OnError and OnClose of delegate, and no more
278  // notifications will be sent to delegate.
279  void Finish(int result);
280
281  int DidEstablishConnection();
282  int DidReceiveData(int result);
283  // Given the number of bytes sent,
284  // - notifies the |delegate_| and |metrics_| of this event.
285  // - drains sent data from |current_write_buf_|.
286  // - if |current_write_buf_| has been fully sent, sets NULL to
287  //   |current_write_buf_| to get ready for next write.
288  // and then, returns OK.
289  void DidSendData(int result);
290
291  void OnIOCompleted(int result);
292  void OnReadCompleted(int result);
293  void OnWriteCompleted(int result);
294
295  void DoLoop(int result);
296
297  int DoBeforeConnect();
298  int DoBeforeConnectComplete(int result);
299  int DoResolveProxy();
300  int DoResolveProxyComplete(int result);
301  int DoResolveHost();
302  int DoResolveHostComplete(int result);
303  int DoResolveProtocol(int result);
304  int DoResolveProtocolComplete(int result);
305  int DoTcpConnect(int result);
306  int DoTcpConnectComplete(int result);
307  int DoGenerateProxyAuthToken();
308  int DoGenerateProxyAuthTokenComplete(int result);
309  int DoWriteTunnelHeaders();
310  int DoWriteTunnelHeadersComplete(int result);
311  int DoReadTunnelHeaders();
312  int DoReadTunnelHeadersComplete(int result);
313  int DoSOCKSConnect();
314  int DoSOCKSConnectComplete(int result);
315  int DoSecureProxyConnect();
316  int DoSecureProxyConnectComplete(int result);
317  int DoSecureProxyHandleCertError(int result);
318  int DoSecureProxyHandleCertErrorComplete(int result);
319  int DoSSLConnect();
320  int DoSSLConnectComplete(int result);
321  int DoSSLHandleCertError(int result);
322  int DoSSLHandleCertErrorComplete(int result);
323  int DoReadWrite(int result);
324
325  GURL ProxyAuthOrigin() const;
326  int HandleAuthChallenge(const HttpResponseHeaders* headers);
327  int HandleCertificateRequest(int result, SSLConfig* ssl_config);
328  void DoAuthRequired();
329  void DoRestartWithAuth();
330
331  int HandleCertificateError(int result);
332  int AllowCertErrorForReconnection(SSLConfig* ssl_config);
333
334  // Returns the sum of the size of buffers in |pending_write_bufs_|.
335  size_t GetTotalSizeOfPendingWriteBufs() const;
336
337  BoundNetLog net_log_;
338
339  GURL url_;
340  // The number of bytes allowed to be buffered in this object. If the size of
341  // buffered data which is
342  //   current_write_buf_.BytesRemaining() +
343  //   sum of the size of buffers in |pending_write_bufs_|
344  // exceeds this limit, SendData() fails.
345  int max_pending_send_allowed_;
346  URLRequestContext* context_;
347
348  UserDataMap user_data_;
349
350  State next_state_;
351  ClientSocketFactory* factory_;
352
353  ProxyMode proxy_mode_;
354
355  GURL proxy_url_;
356  ProxyService::PacRequest* pac_request_;
357  ProxyInfo proxy_info_;
358
359  scoped_refptr<HttpAuthController> proxy_auth_controller_;
360
361  scoped_refptr<RequestHeaders> tunnel_request_headers_;
362  size_t tunnel_request_headers_bytes_sent_;
363  scoped_refptr<ResponseHeaders> tunnel_response_headers_;
364  int tunnel_response_headers_capacity_;
365  int tunnel_response_headers_len_;
366
367  scoped_ptr<SingleRequestHostResolver> resolver_;
368  AddressList addresses_;
369  scoped_ptr<ClientSocketHandle> connection_;
370
371  SSLConfig server_ssl_config_;
372  SSLConfig proxy_ssl_config_;
373  PrivacyMode privacy_mode_;
374
375  CompletionCallback io_callback_;
376
377  scoped_refptr<IOBuffer> read_buf_;
378  int read_buf_size_;
379
380  // Buffer to hold data to pass to socket_.
381  scoped_refptr<DrainableIOBuffer> current_write_buf_;
382  // True iff there's no error and this instance is waiting for completion of
383  // Write operation by socket_.
384  bool waiting_for_write_completion_;
385  PendingDataQueue pending_write_bufs_;
386
387  bool closing_;
388  bool server_closed_;
389
390  scoped_ptr<SocketStreamMetrics> metrics_;
391
392  DISALLOW_COPY_AND_ASSIGN(SocketStream);
393};
394
395}  // namespace net
396
397#endif  // NET_SOCKET_STREAM_SOCKET_STREAM_H_
398