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 CookieOptions;
32class HostResolver;
33class HttpAuthController;
34class SSLInfo;
35class ServerBoundCertService;
36class SingleRequestHostResolver;
37class StreamSocket;
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
193  friend class WebSocketThrottleTest;
194
195  typedef std::map<const void*, linked_ptr<UserData> > UserDataMap;
196  typedef std::deque< scoped_refptr<IOBufferWithSize> > PendingDataQueue;
197
198  class RequestHeaders : public IOBuffer {
199   public:
200    RequestHeaders() : IOBuffer() {}
201
202    void SetDataOffset(size_t offset) {
203      data_ = const_cast<char*>(headers_.data()) + offset;
204    }
205
206    std::string headers_;
207
208    private:
209     virtual ~RequestHeaders();
210  };
211
212  class ResponseHeaders : public IOBuffer {
213   public:
214    ResponseHeaders();
215
216    void SetDataOffset(size_t offset) { data_ = headers_.get() + offset; }
217    char* headers() const { return headers_.get(); }
218    void Reset() { headers_.reset(); }
219    void Realloc(size_t new_size);
220
221   private:
222     virtual ~ResponseHeaders();
223
224    scoped_ptr_malloc<char> headers_;
225  };
226
227  enum State {
228    STATE_NONE,
229    STATE_BEFORE_CONNECT,
230    STATE_BEFORE_CONNECT_COMPLETE,
231    STATE_RESOLVE_PROXY,
232    STATE_RESOLVE_PROXY_COMPLETE,
233    STATE_RESOLVE_HOST,
234    STATE_RESOLVE_HOST_COMPLETE,
235    STATE_RESOLVE_PROTOCOL,
236    STATE_RESOLVE_PROTOCOL_COMPLETE,
237    STATE_TCP_CONNECT,
238    STATE_TCP_CONNECT_COMPLETE,
239    STATE_GENERATE_PROXY_AUTH_TOKEN,
240    STATE_GENERATE_PROXY_AUTH_TOKEN_COMPLETE,
241    STATE_WRITE_TUNNEL_HEADERS,
242    STATE_WRITE_TUNNEL_HEADERS_COMPLETE,
243    STATE_READ_TUNNEL_HEADERS,
244    STATE_READ_TUNNEL_HEADERS_COMPLETE,
245    STATE_SOCKS_CONNECT,
246    STATE_SOCKS_CONNECT_COMPLETE,
247    STATE_SECURE_PROXY_CONNECT,
248    STATE_SECURE_PROXY_CONNECT_COMPLETE,
249    STATE_SECURE_PROXY_HANDLE_CERT_ERROR,
250    STATE_SECURE_PROXY_HANDLE_CERT_ERROR_COMPLETE,
251    STATE_SSL_CONNECT,
252    STATE_SSL_CONNECT_COMPLETE,
253    STATE_SSL_HANDLE_CERT_ERROR,
254    STATE_SSL_HANDLE_CERT_ERROR_COMPLETE,
255    STATE_READ_WRITE,
256    STATE_AUTH_REQUIRED,
257    STATE_CLOSE,
258  };
259
260  enum ProxyMode {
261    kDirectConnection,  // If using a direct connection
262    kTunnelProxy,  // If using a tunnel (CONNECT method as HTTPS)
263    kSOCKSProxy,  // If using a SOCKS proxy
264  };
265
266  // Use the same number as HttpNetworkTransaction::kMaxHeaderBufSize.
267  enum { kMaxTunnelResponseHeadersSize = 32768 };  // 32 kilobytes.
268
269  // Used for WebSocketThrottleTest.
270  void set_addresses(const AddressList& addresses);
271
272  void DoClose();
273
274  // Finishes the job.
275  // Calls OnError and OnClose of delegate, and no more
276  // notifications will be sent to delegate.
277  void Finish(int result);
278
279  int DidEstablishConnection();
280  int DidReceiveData(int result);
281  // Given the number of bytes sent,
282  // - notifies the |delegate_| and |metrics_| of this event.
283  // - drains sent data from |current_write_buf_|.
284  // - if |current_write_buf_| has been fully sent, sets NULL to
285  //   |current_write_buf_| to get ready for next write.
286  // and then, returns OK.
287  void DidSendData(int result);
288
289  void OnIOCompleted(int result);
290  void OnReadCompleted(int result);
291  void OnWriteCompleted(int result);
292
293  void DoLoop(int result);
294
295  int DoBeforeConnect();
296  int DoBeforeConnectComplete(int result);
297  int DoResolveProxy();
298  int DoResolveProxyComplete(int result);
299  int DoResolveHost();
300  int DoResolveHostComplete(int result);
301  int DoResolveProtocol(int result);
302  int DoResolveProtocolComplete(int result);
303  int DoTcpConnect(int result);
304  int DoTcpConnectComplete(int result);
305  int DoGenerateProxyAuthToken();
306  int DoGenerateProxyAuthTokenComplete(int result);
307  int DoWriteTunnelHeaders();
308  int DoWriteTunnelHeadersComplete(int result);
309  int DoReadTunnelHeaders();
310  int DoReadTunnelHeadersComplete(int result);
311  int DoSOCKSConnect();
312  int DoSOCKSConnectComplete(int result);
313  int DoSecureProxyConnect();
314  int DoSecureProxyConnectComplete(int result);
315  int DoSecureProxyHandleCertError(int result);
316  int DoSecureProxyHandleCertErrorComplete(int result);
317  int DoSSLConnect();
318  int DoSSLConnectComplete(int result);
319  int DoSSLHandleCertError(int result);
320  int DoSSLHandleCertErrorComplete(int result);
321  int DoReadWrite(int result);
322
323  GURL ProxyAuthOrigin() const;
324  int HandleAuthChallenge(const HttpResponseHeaders* headers);
325  int HandleCertificateRequest(int result, SSLConfig* ssl_config);
326  void DoAuthRequired();
327  void DoRestartWithAuth();
328
329  int HandleCertificateError(int result);
330  int AllowCertErrorForReconnection(SSLConfig* ssl_config);
331
332  // Returns the sum of the size of buffers in |pending_write_bufs_|.
333  size_t GetTotalSizeOfPendingWriteBufs() const;
334
335  BoundNetLog net_log_;
336
337  GURL url_;
338  // The number of bytes allowed to be buffered in this object. If the size of
339  // buffered data which is
340  //   current_write_buf_.BytesRemaining() +
341  //   sum of the size of buffers in |pending_write_bufs_|
342  // exceeds this limit, SendData() fails.
343  int max_pending_send_allowed_;
344  URLRequestContext* context_;
345
346  UserDataMap user_data_;
347
348  State next_state_;
349  ClientSocketFactory* factory_;
350
351  ProxyMode proxy_mode_;
352
353  GURL proxy_url_;
354  ProxyService::PacRequest* pac_request_;
355  ProxyInfo proxy_info_;
356
357  scoped_refptr<HttpAuthController> proxy_auth_controller_;
358
359  scoped_refptr<RequestHeaders> tunnel_request_headers_;
360  size_t tunnel_request_headers_bytes_sent_;
361  scoped_refptr<ResponseHeaders> tunnel_response_headers_;
362  int tunnel_response_headers_capacity_;
363  int tunnel_response_headers_len_;
364
365  scoped_ptr<SingleRequestHostResolver> resolver_;
366  AddressList addresses_;
367  scoped_ptr<StreamSocket> socket_;
368
369  SSLConfig server_ssl_config_;
370  SSLConfig proxy_ssl_config_;
371  PrivacyMode privacy_mode_;
372
373  CompletionCallback io_callback_;
374
375  scoped_refptr<IOBuffer> read_buf_;
376  int read_buf_size_;
377
378  // Buffer to hold data to pass to socket_.
379  scoped_refptr<DrainableIOBuffer> current_write_buf_;
380  // True iff there's no error and this instance is waiting for completion of
381  // Write operation by socket_.
382  bool waiting_for_write_completion_;
383  PendingDataQueue pending_write_bufs_;
384
385  bool closing_;
386  bool server_closed_;
387
388  scoped_ptr<SocketStreamMetrics> metrics_;
389
390  DISALLOW_COPY_AND_ASSIGN(SocketStream);
391};
392
393}  // namespace net
394
395#endif  // NET_SOCKET_STREAM_SOCKET_STREAM_H_
396