1// Copyright (c) 2011 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#pragma once
8
9#include <deque>
10#include <map>
11#include <string>
12
13#include "base/memory/linked_ptr.h"
14#include "base/memory/ref_counted.h"
15#include "base/memory/scoped_ptr.h"
16#include "base/string16.h"
17#include "base/task.h"
18#include "net/base/address_list.h"
19#include "net/base/completion_callback.h"
20#include "net/base/io_buffer.h"
21#include "net/base/net_log.h"
22#include "net/base/net_errors.h"
23#include "net/base/ssl_config_service.h"
24#include "net/http/http_auth.h"
25#include "net/http/http_auth_cache.h"
26#include "net/http/http_auth_handler.h"
27#include "net/proxy/proxy_service.h"
28#include "net/socket/tcp_client_socket.h"
29#include "net/url_request/url_request_context.h"
30
31namespace net {
32
33class AuthChallengeInfo;
34class ClientSocketFactory;
35class HostResolver;
36class HttpAuthHandlerFactory;
37class SSLConfigService;
38class SingleRequestHostResolver;
39class SocketStreamMetrics;
40
41// SocketStream is used to implement Web Sockets.
42// It provides plain full-duplex stream with proxy and SSL support.
43// For proxy authentication, only basic mechanisum is supported.  It will try
44// authentication identity for proxy URL first.  If server requires proxy
45// authentication, it will try authentication identity for realm that server
46// requests.
47class SocketStream : public base::RefCountedThreadSafe<SocketStream> {
48 public:
49  // Derive from this class and add your own data members to associate extra
50  // information with a SocketStream.  Use GetUserData(key) and
51  // SetUserData(key, data).
52  class UserData {
53   public:
54    UserData() {}
55    virtual ~UserData() {}
56  };
57
58  class Delegate {
59   public:
60    virtual ~Delegate() {}
61
62    virtual int OnStartOpenConnection(SocketStream* socket,
63                                      CompletionCallback* callback) {
64      return OK;
65    }
66
67    // Called when socket stream has been connected.  The socket stream accepts
68    // at most |max_pending_send_allowed| so that a client of the socket stream
69    // should keep track of how much it has pending and shouldn't go over
70    // |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      // By default, no credential is available and close the connection.
91      socket->Close();
92    }
93
94    // Called when an error occured.
95    // This is only for error reporting to the delegate.
96    // |error| is net::Error.
97    virtual void OnError(const SocketStream* socket, int error) {}
98  };
99
100  SocketStream(const GURL& url, Delegate* delegate);
101
102  // The user data allows the clients to associate data with this job.
103  // Multiple user data values can be stored under different keys.
104  // This job will TAKE OWNERSHIP of the given data pointer, and will
105  // delete the object if it is changed or the job is destroyed.
106  UserData* GetUserData(const void* key) const;
107  void SetUserData(const void* key, UserData* data);
108
109  const GURL& url() const { return url_; }
110  bool is_secure() const;
111  const AddressList& address_list() const { return addresses_; }
112  Delegate* delegate() const { return delegate_; }
113  int max_pending_send_allowed() const { return max_pending_send_allowed_; }
114
115  URLRequestContext* context() const { return context_.get(); }
116  void set_context(URLRequestContext* context);
117
118  BoundNetLog* net_log() { return &net_log_; }
119
120  // Opens the connection on the IO thread.
121  // Once the connection is established, calls delegate's OnConnected.
122  virtual void Connect();
123
124  // Requests to send |len| bytes of |data| on the connection.
125  // Returns true if |data| is buffered in the job.
126  // Returns false if size of buffered data would exceeds
127  // |max_pending_send_allowed_| and |data| is not sent at all.
128  virtual bool SendData(const char* data, int len);
129
130  // Requests to close the connection.
131  // Once the connection is closed, calls delegate's OnClose.
132  virtual void Close();
133
134  // Restarts with authentication info.
135  // Should be used for response of OnAuthRequired.
136  virtual void RestartWithAuth(
137      const string16& username,
138      const string16& password);
139
140  // Detach delegate.  Call before delegate is deleted.
141  // Once delegate is detached, close the socket stream and never call delegate
142  // back.
143  virtual void DetachDelegate();
144
145  // Sets an alternative HostResolver. For testing purposes only.
146  void SetHostResolver(HostResolver* host_resolver);
147
148  // Sets an alternative ClientSocketFactory.  Doesn't take ownership of
149  // |factory|.  For testing purposes only.
150  void SetClientSocketFactory(ClientSocketFactory* factory);
151
152 protected:
153  friend class base::RefCountedThreadSafe<SocketStream>;
154  virtual ~SocketStream();
155
156  Delegate* delegate_;
157
158 private:
159  friend class WebSocketThrottleTest;
160
161  typedef std::map<const void*, linked_ptr<UserData> > UserDataMap;
162  typedef std::deque< scoped_refptr<IOBufferWithSize> > PendingDataQueue;
163
164  class RequestHeaders : public IOBuffer {
165   public:
166    RequestHeaders() : IOBuffer() {}
167
168    void SetDataOffset(size_t offset) {
169      data_ = const_cast<char*>(headers_.data()) + offset;
170    }
171
172    std::string headers_;
173
174    private:
175     ~RequestHeaders() { data_ = NULL; }
176  };
177
178  class ResponseHeaders : public IOBuffer {
179   public:
180    ResponseHeaders();
181
182    void SetDataOffset(size_t offset) { data_ = headers_.get() + offset; }
183    char* headers() const { return headers_.get(); }
184    void Reset() { headers_.reset(); }
185    void Realloc(size_t new_size);
186
187   private:
188     ~ResponseHeaders();
189
190    scoped_ptr_malloc<char> headers_;
191  };
192
193  enum State {
194    STATE_NONE,
195    STATE_RESOLVE_PROXY,
196    STATE_RESOLVE_PROXY_COMPLETE,
197    STATE_RESOLVE_HOST,
198    STATE_RESOLVE_HOST_COMPLETE,
199    STATE_TCP_CONNECT,
200    STATE_TCP_CONNECT_COMPLETE,
201    STATE_WRITE_TUNNEL_HEADERS,
202    STATE_WRITE_TUNNEL_HEADERS_COMPLETE,
203    STATE_READ_TUNNEL_HEADERS,
204    STATE_READ_TUNNEL_HEADERS_COMPLETE,
205    STATE_SOCKS_CONNECT,
206    STATE_SOCKS_CONNECT_COMPLETE,
207    STATE_SSL_CONNECT,
208    STATE_SSL_CONNECT_COMPLETE,
209    STATE_READ_WRITE,
210    STATE_AUTH_REQUIRED,
211    STATE_CLOSE,
212  };
213
214  enum ProxyMode {
215    kDirectConnection,  // If using a direct connection
216    kTunnelProxy,  // If using a tunnel (CONNECT method as HTTPS)
217    kSOCKSProxy,  // If using a SOCKS proxy
218  };
219
220  // Use the same number as HttpNetworkTransaction::kMaxHeaderBufSize.
221  enum { kMaxTunnelResponseHeadersSize = 32768 };  // 32 kilobytes.
222
223  // Copies the given addrinfo list in |addresses_|.
224  // Used for WebSocketThrottleTest.
225  void CopyAddrInfo(struct addrinfo* head);
226
227  void DoClose();
228
229  // Finishes the job.
230  // Calls OnError and OnClose of delegate, and no more
231  // notifications will be sent to delegate.
232  void Finish(int result);
233
234  int DidEstablishConnection();
235  int DidReceiveData(int result);
236  int DidSendData(int result);
237
238  void OnIOCompleted(int result);
239  void OnReadCompleted(int result);
240  void OnWriteCompleted(int result);
241
242  void DoLoop(int result);
243
244  int DoResolveProxy();
245  int DoResolveProxyComplete(int result);
246  int DoResolveHost();
247  int DoResolveHostComplete(int result);
248  int DoTcpConnect(int result);
249  int DoTcpConnectComplete(int result);
250  int DoWriteTunnelHeaders();
251  int DoWriteTunnelHeadersComplete(int result);
252  int DoReadTunnelHeaders();
253  int DoReadTunnelHeadersComplete(int result);
254  int DoSOCKSConnect();
255  int DoSOCKSConnectComplete(int result);
256  int DoSSLConnect();
257  int DoSSLConnectComplete(int result);
258  int DoReadWrite(int result);
259
260  GURL ProxyAuthOrigin() const;
261  int HandleAuthChallenge(const HttpResponseHeaders* headers);
262  void DoAuthRequired();
263  void DoRestartWithAuth();
264
265  int HandleCertificateError(int result);
266
267  SSLConfigService* ssl_config_service() const;
268  ProxyService* proxy_service() const;
269
270  BoundNetLog net_log_;
271
272  GURL url_;
273  int max_pending_send_allowed_;
274  scoped_refptr<URLRequestContext> context_;
275
276  UserDataMap user_data_;
277
278  State next_state_;
279  HostResolver* host_resolver_;
280  CertVerifier* cert_verifier_;
281  HttpAuthHandlerFactory* http_auth_handler_factory_;
282  ClientSocketFactory* factory_;
283
284  ProxyMode proxy_mode_;
285
286  GURL proxy_url_;
287  ProxyService::PacRequest* pac_request_;
288  ProxyInfo proxy_info_;
289
290  HttpAuthCache auth_cache_;
291  scoped_ptr<HttpAuthHandler> auth_handler_;
292  HttpAuth::Identity auth_identity_;
293  scoped_refptr<AuthChallengeInfo> auth_info_;
294
295  scoped_refptr<RequestHeaders> tunnel_request_headers_;
296  size_t tunnel_request_headers_bytes_sent_;
297  scoped_refptr<ResponseHeaders> tunnel_response_headers_;
298  int tunnel_response_headers_capacity_;
299  int tunnel_response_headers_len_;
300
301  scoped_ptr<SingleRequestHostResolver> resolver_;
302  AddressList addresses_;
303  scoped_ptr<ClientSocket> socket_;
304
305  SSLConfig ssl_config_;
306
307  CompletionCallbackImpl<SocketStream> io_callback_;
308  CompletionCallbackImpl<SocketStream> read_callback_;
309  CompletionCallbackImpl<SocketStream> write_callback_;
310
311  scoped_refptr<IOBuffer> read_buf_;
312  int read_buf_size_;
313
314  // Total amount of buffer (|write_buf_size_| - |write_buf_offset_| +
315  // sum of size of |pending_write_bufs_|) should not exceed
316  // |max_pending_send_allowed_|.
317  // |write_buf_| holds requested data and |current_write_buf_| is used
318  // for Write operation, that is, |current_write_buf_| is
319  // |write_buf_| + |write_buf_offset_|.
320  scoped_refptr<IOBuffer> write_buf_;
321  scoped_refptr<DrainableIOBuffer> current_write_buf_;
322  int write_buf_offset_;
323  int write_buf_size_;
324  PendingDataQueue pending_write_bufs_;
325
326  bool closing_;
327  bool server_closed_;
328
329  scoped_ptr<SocketStreamMetrics> metrics_;
330
331  DISALLOW_COPY_AND_ASSIGN(SocketStream);
332};
333
334}  // namespace net
335
336#endif  // NET_SOCKET_STREAM_SOCKET_STREAM_H_
337