SocketManager.hpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. * 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. void _closeSockets()
  138. throw();
  139. // Called in SocketManager to recompute _nfds for select() based implementation
  140. void _updateNfds();
  141. #ifdef __WINDOWS__
  142. SOCKET _whackSendPipe;
  143. SOCKET _whackReceivePipe;
  144. SOCKET _tcpV4ListenSocket;
  145. SOCKET _tcpV6ListenSocket;
  146. #else
  147. int _whackSendPipe;
  148. int _whackReceivePipe;
  149. int _tcpV4ListenSocket;
  150. int _tcpV6ListenSocket;
  151. #endif
  152. Mutex _whackSendPipe_m;
  153. SharedPtr<Socket> _udpV4Socket;
  154. SharedPtr<Socket> _udpV6Socket;
  155. fd_set _readfds;
  156. fd_set _writefds;
  157. volatile int _nfds;
  158. Mutex _fdSetLock;
  159. std::map< InetAddress,SharedPtr<Socket> > _tcpSockets;
  160. Mutex _tcpSockets_m;
  161. void (*_packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &);
  162. void *_arg;
  163. Mutex _pollLock;
  164. };
  165. } // namespace ZeroTier
  166. #endif