SocketManager.hpp 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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. private:
  109. // Called by socket implementations when a packet is received
  110. inline void handleReceivedPacket(const SharedPtr<Socket> &sock,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  111. throw()
  112. {
  113. try {
  114. _packetHandler(sock,_arg,from,data);
  115. } catch ( ... ) {} // handlers shouldn't throw
  116. }
  117. // Called by socket implementations to register or unregister for available-for-write notification on underlying _sock
  118. inline void startNotifyWrite(const Socket *sock)
  119. throw()
  120. {
  121. _fdSetLock.lock();
  122. FD_SET(sock->_sock,&_writefds);
  123. _fdSetLock.unlock();
  124. }
  125. inline void stopNotifyWrite(const Socket *sock)
  126. throw()
  127. {
  128. _fdSetLock.lock();
  129. FD_CLR(sock->_sock,&_writefds);
  130. _fdSetLock.unlock();
  131. }
  132. inline void _closeSockets()
  133. throw()
  134. {
  135. #ifdef __WINDOWS__
  136. if (_whackSendPipe != INVALID_SOCKET)
  137. ::closesocket(_whackSendPipe);
  138. if (_whackReceivePipe != INVALID_SOCKET)
  139. ::closesocket(_whackReceivePipe);
  140. if (_tcpV4ListenSocket != INVALID_SOCKET)
  141. ::closesocket(s);
  142. if (_tcpV6ListenSocket != INVALID_SOCKET)
  143. ::closesocket(s);
  144. #else
  145. if (_whackSendPipe > 0)
  146. ::close(_whackSendPipe);
  147. if (_whackReceivePipe > 0)
  148. ::close(_whackReceivePipe);
  149. if (_tcpV4ListenSocket > 0)
  150. ::close(_tcpV4ListenSocket);
  151. if (_tcpV4ListenSocket > 0)
  152. ::close(_tcpV6ListenSocket);
  153. #endif
  154. }
  155. #ifdef __WINDOWS__
  156. SOCKET _whackSendPipe;
  157. SOCKET _whackReceivePipe;
  158. SOCKET _tcpV4ListenSocket;
  159. SOCKET _tcpV6ListenSocket;
  160. #else
  161. int _whackSendPipe;
  162. int _whackReceivePipe;
  163. int _tcpV4ListenSocket;
  164. int _tcpV6ListenSocket;
  165. #endif
  166. Mutex _whackSendPipe_m;
  167. SharedPtr<Socket> _udpV4Socket;
  168. SharedPtr<Socket> _udpV6Socket;
  169. fd_set _readfds;
  170. fd_set _writefds;
  171. int _nfds;
  172. Mutex _fdSetLock;
  173. std::map< InetAddress,SharedPtr<Socket> > _tcpSockets;
  174. Mutex _tcpSockets_m;
  175. void (*_packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &);
  176. void *_arg;
  177. Mutex _pollLock;
  178. };
  179. } // namespace ZeroTier
  180. #endif