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