UDPEndpoint.hpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. /*
  2. Copyright (c) 2009 Christopher A. Taylor. All rights reserved.
  3. Redistribution and use in source and binary forms, with or without
  4. modification, are permitted provided that the following conditions are met:
  5. * Redistributions of source code must retain the above copyright notice,
  6. this list of conditions and the following disclaimer.
  7. * Redistributions in binary form must reproduce the above copyright notice,
  8. this list of conditions and the following disclaimer in the documentation
  9. and/or other materials provided with the distribution.
  10. * Neither the name of LibCat nor the names of its contributors may be used
  11. to endorse or promote products derived from this software without
  12. specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  14. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  17. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  18. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  19. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  20. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  21. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  22. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  23. POSSIBILITY OF SUCH DAMAGE.
  24. */
  25. #ifndef CAT_THREAD_POOL_UDP_ENDPOINT_HPP
  26. #define CAT_THREAD_POOL_UDP_ENDPOINT_HPP
  27. /*
  28. Windows version of thread pool sockets with IO Completion Ports
  29. Included from <cat/net/ThreadPoolSockets.hpp>
  30. Do not include directly
  31. */
  32. #include <MSWSock.h>
  33. #include <cat/port/WindowsInclude.hpp>
  34. namespace cat {
  35. //// Overlapped Sockets
  36. // AcceptEx() OVERLAPPED structure
  37. struct AcceptExOverlapped
  38. {
  39. TypedOverlapped tov;
  40. Socket acceptSocket;
  41. // Space pre-allocated to receive addresses
  42. // NOTE: This is not necessarily how the addresses are organized in memory
  43. struct
  44. {
  45. // Not necessarily an IPv6 address either!
  46. sockaddr_in6 addr[2];
  47. u8 padding[2*16];
  48. } addresses;
  49. void Set(Socket s);
  50. };
  51. // WSARecvFrom() OVERLAPPED structure
  52. struct RecvFromOverlapped
  53. {
  54. TypedOverlapped tov;
  55. // Not necessarily and IPv6 address,
  56. // but we allocate enough space for one
  57. int addrLen;
  58. sockaddr_in6 addr;
  59. // data follows...
  60. void Reset();
  61. };
  62. /*
  63. class TCPServer
  64. Object that represents a TCP server bound to a single port
  65. Overload InstantiateServerConnection() to subclass connections with the server
  66. */
  67. class TCPServer : public ThreadRefObject
  68. {
  69. friend class TCPConnection;
  70. friend class ThreadPool;
  71. public:
  72. TCPServer();
  73. virtual ~TCPServer();
  74. bool ValidServer();
  75. Port GetPort();
  76. bool Bind(Port port = 0);
  77. void Close();
  78. protected:
  79. virtual TCPConnection *InstantiateServerConnection() = 0;
  80. private:
  81. Socket _socket;
  82. LPFN_ACCEPTEX _lpfnAcceptEx;
  83. LPFN_GETACCEPTEXSOCKADDRS _lpfnGetAcceptExSockAddrs;
  84. LPFN_DISCONNECTEX _lpfnDisconnectEx;
  85. Port _port;
  86. private:
  87. bool QueueAcceptEx();
  88. bool QueueAccepts();
  89. void OnAcceptExComplete(int error, AcceptExOverlapped *overlapped);
  90. };
  91. /*
  92. class TCPConnection
  93. Object that represents a TCPServer's connection from a TCPClient
  94. Object is instantiated just before accepting a connection
  95. DisconnectClient() : Disconnect the client
  96. PostToClient() : Send a message to the client
  97. ValidServerConnection() : Returns true iff the connection is valid
  98. OnConnectFromClient() : Return false to deny this connection
  99. OnReadFromClient() : Return false to disconnect the client in response to a message
  100. OnWriteToClient() : Informs the derived class that data has been sent
  101. OnDisconectFromClient() : Informs the derived class that the client has disconnected
  102. */
  103. class TCPConnection : public ThreadRefObject
  104. {
  105. friend class TCPServer;
  106. friend class ThreadPool;
  107. public:
  108. TCPConnection();
  109. virtual ~TCPConnection();
  110. bool ValidServerConnection();
  111. void DisconnectClient();
  112. bool PostToClient(void *buffer, u32 bytes);
  113. protected:
  114. virtual bool OnConnectFromClient(const NetAddr &remoteClientAddress) = 0; // false = disconnect
  115. virtual bool OnReadFromClient(u8 *data, u32 bytes) = 0; // false = disconnect
  116. virtual void OnWriteToClient(u32 bytes) = 0;
  117. virtual void OnDisconnectFromClient() = 0;
  118. private:
  119. Socket _socket;
  120. LPFN_DISCONNECTEX _lpfnDisconnectEx;
  121. TypedOverlapped *_recvOv;
  122. volatile u32 _disconnecting;
  123. private:
  124. bool AcceptConnection(Socket listenSocket, Socket acceptSocket,
  125. LPFN_DISCONNECTEX lpfnDisconnectEx, const NetAddr &acceptAddress,
  126. const NetAddr &remoteClientAddress);
  127. bool QueueWSARecv();
  128. void OnWSARecvComplete(int error, u32 bytes);
  129. bool QueueWSASend(TypedOverlapped *sendOv, u32 bytes);
  130. void OnWSASendComplete(int error, u32 bytes);
  131. bool QueueDisconnectEx();
  132. void OnDisconnectExComplete(int error);
  133. };
  134. /*
  135. class TCPClient
  136. Object that represents a TCPClient bound to a single port
  137. ValidClient() : Returns true iff the client socket is valid
  138. Connect() : Connects to the given address
  139. DisconnectServer() : Disconnects from the server
  140. PostToServer() : Send a message to the server (will fail if not connected)
  141. OnConnectToServer() : Called when connection is accepted
  142. OnReadFromServer() : Return false to disconnect the server in response to data
  143. OnWriteToServer() : Informs the derived class that data has been sent
  144. OnDisconnectFromServer() : Informs the derived class that the server has disconnected
  145. */
  146. class TCPClient : public ThreadRefObject
  147. {
  148. friend class ThreadPool;
  149. public:
  150. TCPClient();
  151. virtual ~TCPClient();
  152. bool ValidClient();
  153. bool Connect(const NetAddr &remoteServerAddress);
  154. void DisconnectServer();
  155. bool PostToServer(void *buffer, u32 bytes);
  156. protected:
  157. virtual void OnConnectToServer() = 0;
  158. virtual bool OnReadFromServer(u8 *data, u32 bytes) = 0; // false = disconnect
  159. virtual void OnWriteToServer(u32 bytes) = 0;
  160. virtual void OnDisconnectFromServer() = 0;
  161. private:
  162. Socket _socket;
  163. TypedOverlapped *_recvOv;
  164. volatile u32 _disconnecting;
  165. bool _ipv6;
  166. private:
  167. bool QueueConnectEx(const NetAddr &remoteServerAddress);
  168. void OnConnectExComplete(int error);
  169. bool QueueWSARecv();
  170. void OnWSARecvComplete(int error, u32 bytes);
  171. bool QueueWSASend(TypedOverlapped *sendOv, u32 bytes);
  172. void OnWSASendComplete(int error, u32 bytes);
  173. bool QueueDisconnectEx();
  174. void OnDisconnectExComplete(int error);
  175. };
  176. /*
  177. class TCPClientQueued
  178. Base class for a TCP client that needs to queue up data for sending before
  179. a connection has been established. e.g. Uplink for a proxy server.
  180. PostQueuedToServer() : Call in OnConnectToServer() to post the queued messages.
  181. */
  182. class TCPClientQueued : public TCPClient
  183. {
  184. private:
  185. volatile bool _queuing;
  186. Mutex _queueLock;
  187. void *_queueBuffer;
  188. u32 _queueBytes;
  189. protected:
  190. void PostQueuedToServer();
  191. public:
  192. TCPClientQueued();
  193. virtual ~TCPClientQueued();
  194. bool PostToServer(void *buffer, u32 bytes);
  195. };
  196. /*
  197. class UDPEndpoint
  198. Object that represents a UDP endpoint bound to a single port
  199. */
  200. class UDPEndpoint : public ThreadRefObject
  201. {
  202. friend class ThreadPool;
  203. public:
  204. UDPEndpoint();
  205. virtual ~UDPEndpoint();
  206. bool Valid();
  207. Port GetPort();
  208. // Is6() result is only valid AFTER Bind()
  209. CAT_INLINE bool Is6() { return _ipv6; }
  210. // For servers: Bind() with ignoreUnreachable = true ((default))
  211. // For clients: Bind() with ignoreUnreachable = false and call this
  212. // after the first packet from the server is received.
  213. bool IgnoreUnreachable();
  214. void Close(); // Invalidates this object
  215. bool Bind(Port port = 0, bool ignoreUnreachable = true);
  216. bool QueueWSARecvFrom();
  217. // If Is6() == true, the address must be promoted to IPv6
  218. // before calling Post() with addr.PromoteTo6()
  219. bool Post(const NetAddr &addr, void *data, u32 bytes);
  220. protected:
  221. virtual void OnRead(ThreadPoolLocalStorage *tls, const NetAddr &addr, u8 *data, u32 bytes) = 0; // false = close
  222. virtual void OnWrite(u32 bytes) = 0;
  223. virtual void OnClose() = 0;
  224. virtual void OnUnreachable(const NetAddr &addr) {} // Only IP is valid
  225. private:
  226. Socket _socket;
  227. Port _port;
  228. volatile u32 _closing;
  229. bool _ipv6;
  230. private:
  231. bool QueueWSARecvFrom(RecvFromOverlapped *recvOv);
  232. void OnWSARecvFromComplete(ThreadPoolLocalStorage *tls, int error, RecvFromOverlapped *recvOv, u32 bytes);
  233. bool QueueWSASendTo(const NetAddr &addr, TypedOverlapped *sendOv, u32 bytes);
  234. void OnWSASendToComplete(int error, u32 bytes);
  235. };
  236. } // namespace cat
  237. #endif // CAT_THREAD_POOL_UDP_ENDPOINT_HPP
粤ICP备19079148号