SocketManager.hpp 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. * Perform I/O polling operation (e.g. select())
  95. *
  96. * If called concurrently, one will block until the other completes.
  97. *
  98. * @param timeout Timeout in milliseconds, may return sooner if whack() is called
  99. */
  100. void poll(unsigned long timeout);
  101. /**
  102. * Cause current or next blocking poll() operation to timeout immediately
  103. */
  104. void whack();
  105. /**
  106. * Close TCP sockets
  107. */
  108. void closeTcpSockets();
  109. private:
  110. // Called by socket implementations when a packet is received
  111. inline void handleReceivedPacket(const SharedPtr<Socket> &sock,const InetAddress &from,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &data)
  112. throw()
  113. {
  114. try {
  115. _packetHandler(sock,_arg,from,data);
  116. } catch ( ... ) {} // handlers shouldn't throw
  117. }
  118. // Used by TcpSocket to register/unregister for write availability notification
  119. inline void startNotifyWrite(const Socket *sock)
  120. throw()
  121. {
  122. _fdSetLock.lock();
  123. FD_SET(sock->_sock,&_writefds);
  124. _fdSetLock.unlock();
  125. }
  126. inline void stopNotifyWrite(const Socket *sock)
  127. throw()
  128. {
  129. _fdSetLock.lock();
  130. FD_CLR(sock->_sock,&_writefds);
  131. _fdSetLock.unlock();
  132. }
  133. // Called in SocketManager destructor or in constructor cleanup before exception throwing
  134. void _closeSockets()
  135. throw();
  136. // Called in SocketManager to recompute _nfds for select() based implementation
  137. void _updateNfds();
  138. #ifdef __WINDOWS__
  139. SOCKET _whackSendPipe;
  140. SOCKET _whackReceivePipe;
  141. SOCKET _tcpV4ListenSocket;
  142. SOCKET _tcpV6ListenSocket;
  143. #else
  144. int _whackSendPipe;
  145. int _whackReceivePipe;
  146. int _tcpV4ListenSocket;
  147. int _tcpV6ListenSocket;
  148. #endif
  149. Mutex _whackSendPipe_m;
  150. SharedPtr<Socket> _udpV4Socket;
  151. SharedPtr<Socket> _udpV6Socket;
  152. fd_set _readfds;
  153. fd_set _writefds;
  154. volatile int _nfds;
  155. Mutex _fdSetLock;
  156. std::map< InetAddress,SharedPtr<Socket> > _tcpSockets;
  157. Mutex _tcpSockets_m;
  158. void (*_packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &);
  159. void *_arg;
  160. Mutex _pollLock;
  161. };
  162. } // namespace ZeroTier
  163. #endif