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