SocketManager.hpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #ifndef ZT_SOCKETMANAGER_HPP
  28. #define ZT_SOCKETMANAGER_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #ifdef __WINDOWS__
  32. #include <WinSock2.h>
  33. #include <WS2tcpip.h>
  34. #include <Windows.h>
  35. #else
  36. #include <unistd.h>
  37. #include <sys/time.h>
  38. #include <sys/types.h>
  39. #include <sys/select.h>
  40. #endif
  41. #include <map>
  42. #include <stdexcept>
  43. #include "Constants.hpp"
  44. #include "SharedPtr.hpp"
  45. #include "InetAddress.hpp"
  46. #include "Socket.hpp"
  47. #include "TcpSocket.hpp"
  48. #include "UdpSocket.hpp"
  49. #include "Mutex.hpp"
  50. #include "NonCopyable.hpp"
  51. #include "Buffer.hpp"
  52. namespace ZeroTier {
  53. /**
  54. * Socket I/O multiplexer
  55. *
  56. * This wraps select(), epoll(), etc. and handles creation of Sockets.
  57. */
  58. class SocketManager : NonCopyable
  59. {
  60. friend class Socket;
  61. friend class UdpSocket;
  62. friend class TcpSocket;
  63. public:
  64. /**
  65. * @param localUdpPort Local UDP port to bind or 0 for no UDP support
  66. * @param localTcpPort Local TCP port to listen to or 0 for no incoming TCP connect support
  67. * @param packetHandler Function to call when packets are received by a socket
  68. * @param arg Second argument to packetHandler()
  69. * @throws std::runtime_error Could not bind local port(s) or open socket(s)
  70. */
  71. SocketManager(int localUdpPort,int localTcpPort,void (*packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &),void *arg);
  72. ~SocketManager();
  73. /**
  74. * Send a message to a remote peer
  75. *
  76. * If 'tcp' is true an existing TCP socket will be used or an attempt will
  77. * be made to connect if one is not available. The message will be placed
  78. * in the connecting TCP socket's outgoing queue, so if the connection
  79. * succeeds the message will be sent. Otherwise it will be dropped.
  80. *
  81. * @param to Destination address
  82. * @param tcp Use TCP?
  83. * @param msg Message to send
  84. * @param msglen Length of message
  85. */
  86. bool send(const InetAddress &to,bool tcp,const void *msg,unsigned int msglen);
  87. /**
  88. * Send a UDP packet with a limited IP TTL
  89. *
  90. * @param to Destination address
  91. * @param hopLimit IP TTL
  92. */
  93. bool sendFirewallOpener(const InetAddress &to,int hopLimit);
  94. /**
  95. * Perform I/O polling operation (e.g. select())
  96. *
  97. * If called concurrently, one will block until the other completes.
  98. *
  99. * @param timeout Timeout in milliseconds, may return sooner if whack() is called
  100. */
  101. void poll(unsigned long timeout);
  102. /**
  103. * Cause current or next blocking poll() operation to timeout immediately
  104. */
  105. void whack();
  106. private:
  107. // Called by socket implementations when a packet is received
  108. inline void handleReceivedPacket(const SharedPtr<Socket> &sock,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  109. throw()
  110. {
  111. try {
  112. _packetHandler(sock,_arg,from,data);
  113. } catch ( ... ) {} // handlers shouldn't throw
  114. }
  115. // Called by socket implementations to register or unregister for available-for-write notification on underlying _sock
  116. inline void startNotifyWrite(const Socket *sock)
  117. throw()
  118. {
  119. _fdSetLock.lock();
  120. FD_SET(sock->_sock,&_writefds);
  121. _fdSetLock.unlock();
  122. }
  123. inline void stopNotifyWrite(const Socket *sock)
  124. throw()
  125. {
  126. _fdSetLock.lock();
  127. FD_CLR(sock->_sock,&_writefds);
  128. _fdSetLock.unlock();
  129. }
  130. inline void _closeSockets()
  131. throw()
  132. {
  133. #ifdef __WINDOWS__
  134. if (_whackSendPipe != INVALID_SOCKET)
  135. ::closesocket(_whackSendPipe);
  136. if (_whackReceivePipe != INVALID_SOCKET)
  137. ::closesocket(_whackReceivePipe);
  138. if (_tcpV4ListenSocket != INVALID_SOCKET)
  139. ::closesocket(s);
  140. if (_tcpV6ListenSocket != INVALID_SOCKET)
  141. ::closesocket(s);
  142. #else
  143. if (_whackSendPipe > 0)
  144. ::close(_whackSendPipe);
  145. if (_whackReceivePipe > 0)
  146. ::close(_whackReceivePipe);
  147. if (_tcpV4ListenSocket > 0)
  148. ::close(_tcpV4ListenSocket);
  149. if (_tcpV4ListenSocket > 0)
  150. ::close(_tcpV6ListenSocket);
  151. #endif
  152. }
  153. #ifdef __WINDOWS__
  154. SOCKET _whackSendPipe;
  155. SOCKET _whackReceivePipe;
  156. #else
  157. int _whackSendPipe;
  158. int _whackReceivePipe;
  159. #endif
  160. Mutex::Lock _whackSendPipe_m;
  161. #ifdef __WINDOWS__
  162. SOCKET _tcpV4ListenSocket;
  163. SOCKET _tcpV6ListenSocket;
  164. #else
  165. int _tcpV4ListenSocket;
  166. int _tcpV6ListenSocket;
  167. #endif
  168. SharedPtr<Socket> _udpV4Socket;
  169. SharedPtr<Socket> _udpV6Socket;
  170. fd_set _readfds;
  171. fd_set _writefds;
  172. int _nfds;
  173. Mutex _fdSetLock;
  174. std::map< InetAddress,SharedPtr<Socket> > _tcpSockets;
  175. Mutex _tcpSockets_m;
  176. void (*_packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &);
  177. void *_arg;
  178. Mutex _pollLock;
  179. };
  180. } // namespace ZeroTier
  181. #endif