SocketManager.hpp 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. #include <map>
  32. #include <stdexcept>
  33. #include "Constants.hpp"
  34. #include "SharedPtr.hpp"
  35. #include "InetAddress.hpp"
  36. #include "Socket.hpp"
  37. #include "Mutex.hpp"
  38. #include "NonCopyable.hpp"
  39. #include "Buffer.hpp"
  40. #ifdef __WINDOWS__
  41. #include <WinSock2.h>
  42. #include <WS2tcpip.h>
  43. #include <Windows.h>
  44. #else
  45. #include <unistd.h>
  46. #include <sys/time.h>
  47. #include <sys/types.h>
  48. #include <sys/select.h>
  49. #endif
  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. * @param to Destination address
  79. * @param tcp Use TCP?
  80. * @param autoConnectTcp If true, automatically initiate TCP connection if there is none
  81. * @param msg Message to send
  82. * @param msglen Length of message
  83. */
  84. bool send(const InetAddress &to,bool tcp,bool autoConnectTcp,const void *msg,unsigned int msglen);
  85. /**
  86. * Send a message to a remote peer via UDP (shortcut for setting both TCP params to false in send)
  87. *
  88. * @param to Destination address
  89. * @param msg Message to send
  90. * @param msglen Length of message
  91. */
  92. inline bool sendUdp(const InetAddress &to,const void *msg,unsigned int msglen) { return send(to,false,false,msg,msglen); }
  93. /**
  94. * Send a UDP packet with a limited IP TTL
  95. *
  96. * @param to Destination address
  97. * @param hopLimit IP TTL
  98. */
  99. #ifdef ZT_FIREWALL_OPENER_DELAY
  100. bool sendFirewallOpener(const InetAddress &to,int hopLimit);
  101. #endif
  102. /**
  103. * Perform I/O polling operation (e.g. select())
  104. *
  105. * If called concurrently, one will block until the other completes.
  106. *
  107. * @param timeout Timeout in milliseconds, may return sooner if whack() is called
  108. */
  109. void poll(unsigned long timeout);
  110. /**
  111. * Cause current or next blocking poll() operation to timeout immediately
  112. */
  113. void whack();
  114. /**
  115. * Close TCP sockets
  116. */
  117. void closeTcpSockets();
  118. private:
  119. // Called by socket implementations when a packet is received
  120. inline void handleReceivedPacket(const SharedPtr<Socket> &sock,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  121. throw()
  122. {
  123. try {
  124. _packetHandler(sock,_arg,from,data);
  125. } catch ( ... ) {} // handlers shouldn't throw
  126. }
  127. // Used by TcpSocket to register/unregister for write availability notification
  128. inline void startNotifyWrite(const Socket *sock)
  129. throw()
  130. {
  131. _fdSetLock.lock();
  132. FD_SET(sock->_sock,&_writefds);
  133. _fdSetLock.unlock();
  134. }
  135. inline void stopNotifyWrite(const Socket *sock)
  136. throw()
  137. {
  138. _fdSetLock.lock();
  139. FD_CLR(sock->_sock,&_writefds);
  140. _fdSetLock.unlock();
  141. }
  142. // Called in SocketManager destructor or in constructor cleanup before exception throwing
  143. void _closeSockets()
  144. throw();
  145. // Called in SocketManager to recompute _nfds for select() based implementation
  146. void _updateNfds();
  147. #ifdef __WINDOWS__
  148. SOCKET _whackSendPipe;
  149. SOCKET _whackReceivePipe;
  150. SOCKET _tcpV4ListenSocket;
  151. SOCKET _tcpV6ListenSocket;
  152. #else
  153. int _whackSendPipe;
  154. int _whackReceivePipe;
  155. int _tcpV4ListenSocket;
  156. int _tcpV6ListenSocket;
  157. #endif
  158. Mutex _whackSendPipe_m;
  159. SharedPtr<Socket> _udpV4Socket;
  160. SharedPtr<Socket> _udpV6Socket;
  161. fd_set _readfds;
  162. fd_set _writefds;
  163. volatile int _nfds;
  164. Mutex _fdSetLock;
  165. std::map< InetAddress,SharedPtr<Socket> > _tcpSockets;
  166. Mutex _tcpSockets_m;
  167. void (*_packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &);
  168. void *_arg;
  169. Mutex _pollLock;
  170. };
  171. } // namespace ZeroTier
  172. #endif