SocketManager.hpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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 "Mutex.hpp"
  48. #include "NonCopyable.hpp"
  49. #include "Buffer.hpp"
  50. namespace ZeroTier {
  51. /**
  52. * Socket I/O multiplexer
  53. *
  54. * This wraps select(), epoll(), etc. and handles creation of Sockets.
  55. */
  56. class SocketManager : NonCopyable
  57. {
  58. friend class Socket;
  59. friend class UdpSocket;
  60. friend class TcpSocket;
  61. public:
  62. /**
  63. * @param localUdpPort Local UDP port to bind or 0 for no UDP support
  64. * @param localTcpPort Local TCP port to listen to or 0 for no incoming TCP connect support
  65. * @param packetHandler Function to call when packets are received by a socket
  66. * @param arg Second argument to packetHandler()
  67. * @throws std::runtime_error Could not bind local port(s) or open socket(s)
  68. */
  69. SocketManager(
  70. int localUdpPort,
  71. int localTcpPort,
  72. void (*packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &),
  73. void *arg);
  74. ~SocketManager();
  75. /**
  76. * Send a message to a remote peer
  77. *
  78. * If 'tcp' is true an existing TCP socket will be used or an attempt will
  79. * be made to connect if one is not available. The message will be placed
  80. * in the connecting TCP socket's outgoing queue, so if the connection
  81. * succeeds the message will be sent. Otherwise it will be dropped.
  82. *
  83. * @param to Destination address
  84. * @param tcp Use TCP?
  85. * @param msg Message to send
  86. * @param msglen Length of message
  87. */
  88. bool send(const InetAddress &to,bool tcp,const void *msg,unsigned int msglen);
  89. /**
  90. * Send a UDP packet with a limited IP TTL
  91. *
  92. * @param to Destination address
  93. * @param hopLimit IP TTL
  94. */
  95. bool sendFirewallOpener(const InetAddress &to,int hopLimit);
  96. /**
  97. * Perform I/O polling operation (e.g. select())
  98. *
  99. * If called concurrently, one will block until the other completes.
  100. *
  101. * @param timeout Timeout in milliseconds, may return sooner if whack() is called
  102. */
  103. void poll(unsigned long timeout);
  104. /**
  105. * Cause current or next blocking poll() operation to timeout immediately
  106. */
  107. void whack();
  108. /**
  109. * Close TCP sockets
  110. */
  111. void closeTcpSockets();
  112. private:
  113. // Called by socket implementations when a packet is received
  114. inline void handleReceivedPacket(const SharedPtr<Socket> &sock,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  115. throw()
  116. {
  117. try {
  118. _packetHandler(sock,_arg,from,data);
  119. } catch ( ... ) {} // handlers shouldn't throw
  120. }
  121. // Used by TcpSocket to register/unregister for write availability notification
  122. inline void startNotifyWrite(const Socket *sock)
  123. throw()
  124. {
  125. _fdSetLock.lock();
  126. FD_SET(sock->_sock,&_writefds);
  127. _fdSetLock.unlock();
  128. }
  129. inline void stopNotifyWrite(const Socket *sock)
  130. throw()
  131. {
  132. _fdSetLock.lock();
  133. FD_CLR(sock->_sock,&_writefds);
  134. _fdSetLock.unlock();
  135. }
  136. // Called in SocketManager destructor or in constructor cleanup before exception throwing
  137. inline void _closeSockets()
  138. throw()
  139. {
  140. #ifdef __WINDOWS__
  141. if (_whackSendPipe != INVALID_SOCKET)
  142. ::closesocket(_whackSendPipe);
  143. if (_whackReceivePipe != INVALID_SOCKET)
  144. ::closesocket(_whackReceivePipe);
  145. if (_tcpV4ListenSocket != INVALID_SOCKET)
  146. ::closesocket(s);
  147. if (_tcpV6ListenSocket != INVALID_SOCKET)
  148. ::closesocket(s);
  149. #else
  150. if (_whackSendPipe > 0)
  151. ::close(_whackSendPipe);
  152. if (_whackReceivePipe > 0)
  153. ::close(_whackReceivePipe);
  154. if (_tcpV4ListenSocket > 0)
  155. ::close(_tcpV4ListenSocket);
  156. if (_tcpV4ListenSocket > 0)
  157. ::close(_tcpV6ListenSocket);
  158. #endif
  159. }
  160. inline void _updateNfds()
  161. {
  162. int nfds = _whackSendPipe;
  163. if (_whackReceivePipe > nfds)
  164. nfds = _whackReceivePipe;
  165. if (_tcpV4ListenSocket > nfds)
  166. nfds = _tcpV4ListenSocket;
  167. if (_tcpV6ListenSocket > nfds)
  168. nfds = _tcpV6ListenSocket;
  169. if ((_udpV4Socket)&&(_udpV4Socket->_sock > nfds))
  170. nfds = _udpV4Socket->_sock;
  171. if ((_udpV6Socket)&&(_udpV6Socket->_sock > nfds))
  172. nfds = _udpV6Socket->_sock;
  173. Mutex::Lock _l(_tcpSockets_m);
  174. for(std::map< InetAddress,SharedPtr<Socket> >::const_iterator s(_tcpSockets.begin());s!=_tcpSockets.end();++s) {
  175. if (s->second->_sock > nfds)
  176. nfds = s->second->_sock;
  177. }
  178. _nfds = nfds;
  179. }
  180. #ifdef __WINDOWS__
  181. SOCKET _whackSendPipe;
  182. SOCKET _whackReceivePipe;
  183. SOCKET _tcpV4ListenSocket;
  184. SOCKET _tcpV6ListenSocket;
  185. #else
  186. int _whackSendPipe;
  187. int _whackReceivePipe;
  188. int _tcpV4ListenSocket;
  189. int _tcpV6ListenSocket;
  190. #endif
  191. Mutex _whackSendPipe_m;
  192. SharedPtr<Socket> _udpV4Socket;
  193. SharedPtr<Socket> _udpV6Socket;
  194. fd_set _readfds;
  195. fd_set _writefds;
  196. volatile int _nfds;
  197. Mutex _fdSetLock;
  198. std::map< InetAddress,SharedPtr<Socket> > _tcpSockets;
  199. Mutex _tcpSockets_m;
  200. void (*_packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &);
  201. void *_arg;
  202. Mutex _pollLock;
  203. };
  204. } // namespace ZeroTier
  205. #endif