Home | History | Annotate | Download | only in socket
      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 // Stream-based listen socket implementation that handles reading and writing
      6 // to the socket, but does not handle creating the socket nor connecting
      7 // sockets, which are handled by subclasses on creation and in Accept,
      8 // respectively.
      9 
     10 // StreamListenSocket handles IO asynchronously in the specified MessageLoop.
     11 // This class is NOT thread safe. It uses WSAEVENT handles to monitor activity
     12 // in a given MessageLoop. This means that callbacks will happen in that loop's
     13 // thread always and that all other methods (including constructor and
     14 // destructor) should also be called from the same thread.
     15 
     16 #ifndef NET_SOCKET_STREAM_LISTEN_SOCKET_H_
     17 #define NET_SOCKET_STREAM_LISTEN_SOCKET_H_
     18 
     19 #include "build/build_config.h"
     20 
     21 #if defined(OS_WIN)
     22 #include <winsock2.h>
     23 #endif
     24 #include <string>
     25 #if defined(OS_WIN)
     26 #include "base/win/object_watcher.h"
     27 #elif defined(OS_POSIX)
     28 #include "base/message_loop/message_loop.h"
     29 #endif
     30 
     31 #include "base/basictypes.h"
     32 #include "base/compiler_specific.h"
     33 #include "net/base/net_export.h"
     34 #include "net/socket/stream_listen_socket.h"
     35 
     36 #if defined(OS_POSIX)
     37 typedef int SocketDescriptor;
     38 #else
     39 typedef SOCKET SocketDescriptor;
     40 #endif
     41 
     42 namespace net {
     43 
     44 class IPEndPoint;
     45 
     46 class NET_EXPORT StreamListenSocket
     47     : public base::RefCountedThreadSafe<StreamListenSocket>,
     48 #if defined(OS_WIN)
     49       public base::win::ObjectWatcher::Delegate {
     50 #elif defined(OS_POSIX)
     51       public base::MessageLoopForIO::Watcher {
     52 #endif
     53 
     54  public:
     55   // TODO(erikkay): this delegate should really be split into two parts
     56   // to split up the listener from the connected socket.  Perhaps this class
     57   // should be split up similarly.
     58   class Delegate {
     59    public:
     60     // |server| is the original listening Socket, connection is the new
     61     // Socket that was created.  Ownership of |connection| is transferred
     62     // to the delegate with this call.
     63     virtual void DidAccept(StreamListenSocket* server,
     64                            StreamListenSocket* connection) = 0;
     65     virtual void DidRead(StreamListenSocket* connection,
     66                          const char* data,
     67                          int len) = 0;
     68     virtual void DidClose(StreamListenSocket* sock) = 0;
     69 
     70    protected:
     71     virtual ~Delegate() {}
     72   };
     73 
     74   // Send data to the socket.
     75   void Send(const char* bytes, int len, bool append_linefeed = false);
     76   void Send(const std::string& str, bool append_linefeed = false);
     77 
     78   // Copies the local address to |address|. Returns a network error code.
     79   int GetLocalAddress(IPEndPoint* address);
     80 
     81   static const SocketDescriptor kInvalidSocket;
     82   static const int kSocketError;
     83 
     84  protected:
     85   enum WaitState {
     86     NOT_WAITING      = 0,
     87     WAITING_ACCEPT   = 1,
     88     WAITING_READ     = 2
     89   };
     90 
     91   StreamListenSocket(SocketDescriptor s, Delegate* del);
     92   virtual ~StreamListenSocket();
     93 
     94   SocketDescriptor AcceptSocket();
     95   virtual void Accept() = 0;
     96 
     97   void Listen();
     98   void Read();
     99   void Close();
    100   void CloseSocket(SocketDescriptor s);
    101 
    102   // Pass any value in case of Windows, because in Windows
    103   // we are not using state.
    104   void WatchSocket(WaitState state);
    105   void UnwatchSocket();
    106 
    107   Delegate* const socket_delegate_;
    108 
    109  private:
    110   friend class base::RefCountedThreadSafe<StreamListenSocket>;
    111   friend class TransportClientSocketTest;
    112 
    113   void SendInternal(const char* bytes, int len);
    114 
    115 #if defined(OS_WIN)
    116   // ObjectWatcher delegate.
    117   virtual void OnObjectSignaled(HANDLE object);
    118   base::win::ObjectWatcher watcher_;
    119   HANDLE socket_event_;
    120 #elif defined(OS_POSIX)
    121   // Called by MessagePumpLibevent when the socket is ready to do I/O.
    122   virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
    123   virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE;
    124   WaitState wait_state_;
    125   // The socket's libevent wrapper.
    126   base::MessageLoopForIO::FileDescriptorWatcher watcher_;
    127 #endif
    128 
    129   // NOTE: This is for unit test use only!
    130   // Pause/Resume calling Read(). Note that ResumeReads() will also call
    131   // Read() if there is anything to read.
    132   void PauseReads();
    133   void ResumeReads();
    134 
    135   const SocketDescriptor socket_;
    136   bool reads_paused_;
    137   bool has_pending_reads_;
    138 
    139   DISALLOW_COPY_AND_ASSIGN(StreamListenSocket);
    140 };
    141 
    142 // Abstract factory that must be subclassed for each subclass of
    143 // StreamListenSocket.
    144 class NET_EXPORT StreamListenSocketFactory {
    145  public:
    146   virtual ~StreamListenSocketFactory() {}
    147 
    148   // Returns a new instance of StreamListenSocket or NULL if an error occurred.
    149   virtual scoped_refptr<StreamListenSocket> CreateAndListen(
    150       StreamListenSocket::Delegate* delegate) const = 0;
    151 };
    152 
    153 }  // namespace net
    154 
    155 #endif  // NET_SOCKET_STREAM_LISTEN_SOCKET_H_
    156