SocketManager.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. #include <stdio.h>
  28. #include <string.h>
  29. #include <stdlib.h>
  30. #include <fcntl.h>
  31. #include <time.h>
  32. #include <sys/types.h>
  33. #include "SocketManager.hpp"
  34. #ifndef __WINDOWS__
  35. #include <unistd.h>
  36. #include <sys/socket.h>
  37. #include <arpa/inet.h>
  38. #include <signal.h>
  39. #endif
  40. // Allow us to use the same value on Windows and *nix
  41. #ifndef INVALID_SOCKET
  42. #define INVALID_SOCKET 0
  43. #endif
  44. namespace ZeroTier {
  45. #ifdef __WINDOWS__
  46. // hack from StackOverflow, behaves a bit like pipe() on *nix systems
  47. static inline void __winpipe(SOCKET fds[2])
  48. {
  49. struct sockaddr_in inaddr;
  50. struct sockaddr addr;
  51. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  52. memset(&inaddr, 0, sizeof(inaddr));
  53. memset(&addr, 0, sizeof(addr));
  54. inaddr.sin_family = AF_INET;
  55. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  56. inaddr.sin_port = 0;
  57. int yes=1;
  58. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  59. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  60. listen(lst,1);
  61. int len=sizeof(inaddr);
  62. getsockname(lst, &addr,&len);
  63. fds[0]=::socket(AF_INET, SOCK_STREAM,0);
  64. connect(fds[0],&addr,len);
  65. fds[1]=accept(lst,0,0);
  66. closesocket(lst);
  67. }
  68. #endif
  69. SocketManager::SocketManager(int localUdpPort,int localTcpPort,void (*packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,const void *,unsigned int),void *arg) :
  70. _whackSendPipe(INVALID_SOCKET),
  71. _whackReceivePipe(INVALID_SOCKET),
  72. _tcpV4ListenSocket(INVALID_SOCKET),
  73. _tcpV6ListenSocket(INVALID_SOCKET),
  74. _nfds(0),
  75. _packetHandler(packetHandler),
  76. _arg(arg)
  77. {
  78. FD_ZERO(&_readfds);
  79. FD_ZERO(&_writefds);
  80. #ifdef __WINDOWS__
  81. {
  82. SOCKET tmps[2] = { INVALID_SOCKET,INVALID_SOCKET };
  83. __winpipe(tmps);
  84. _whackSendPipe = tmps[0];
  85. _whackReceivePipe = tmps[1];
  86. }
  87. #else
  88. {
  89. int tmpfds[2];
  90. if (::pipe(tmpfds,0))
  91. throw std::runtime_error("pipe() failed");
  92. _whackSendPipe = tmpfds[1];
  93. _whackReceivePipe = tmpfds[0];
  94. }
  95. #endif
  96. FD_SET(_whackReceivePipe,&_readfds);
  97. if (localTcpPort > 0) {
  98. if (localTcpPort > 0xffff) {
  99. _closeSockets();
  100. throw std::runtime_error("invalid local TCP port number");
  101. }
  102. { // bind TCP IPv6
  103. _tcpV6ListenSocket = ::socket(AF_INET6,SOCK_STREAM,0);
  104. #ifdef __WINDOWS__
  105. if (_tcpV6ListenSocket == INVALID_SOCKET) {
  106. _closeSockets();
  107. throw std::runtime_error("unable to create IPv6 SOCK_STREAM socket");
  108. }
  109. #else
  110. if (_tcpV6ListenSocket <= 0) {
  111. _closeSockets();
  112. throw std::runtime_error("unable to create IPv6 SOCK_STREAM socket");
  113. }
  114. #endif
  115. #ifdef __WINDOWS__
  116. {
  117. BOOL f;
  118. f = TRUE; ::setsockopt(_tcpV6ListenSocket,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  119. f = TRUE; ::setsockopt(_tcpV6ListenSocket,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  120. }
  121. #else
  122. {
  123. int f;
  124. f = 1; ::setsockopt(_tcpV6ListenSocket,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  125. f = 1; ::setsockopt(_tcpV6ListenSocket,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  126. }
  127. #endif
  128. struct sockaddr_in6 sin6;
  129. memset(&sin6,0,sizeof(sin6));
  130. sin6.sin6_family = AF_INET6;
  131. sin6.sin6_port = htons(localTcpPort);
  132. memcpy(&(sin6.sin6_addr),&in6addr_any,sizeof(struct in6_addr));
  133. if (::bind(_tcpV6ListenSocket,(const struct sockaddr *)&sin6,sizeof(sin6))) {
  134. _closeSockets();
  135. throw std::runtime_error("unable to bind to local TCP port");
  136. }
  137. if (::listen(_tcpV6ListenSocket,16)) {
  138. _closeSockets();
  139. throw std::runtime_error("listen() failed");
  140. }
  141. FD_SET(_tcpV6ListenSocket,&_readfds);
  142. }
  143. { // bind TCP IPv4
  144. _tcpV4ListenSocket = ::socket(AF_INET,SOCK_STREAM,0);
  145. #ifdef __WINDOWS__
  146. if (_tcpV4ListenSocket == INVALID_SOCKET) {
  147. _closeSockets();
  148. throw std::runtime_error("unable to create IPv4 SOCK_STREAM socket");
  149. }
  150. #else
  151. if (_tcpV4ListenSocket <= 0) {
  152. _closeSockets();
  153. throw std::runtime_error("unable to create IPv4 SOCK_STREAM socket");
  154. }
  155. #endif
  156. #ifdef __WINDOWS__
  157. {
  158. BOOL f = TRUE; ::setsockopt(_tcpV4ListenSocket,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  159. }
  160. #else
  161. {
  162. int f = 1; ::setsockopt(_tcpV4ListenSocket,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  163. }
  164. #endif
  165. struct sockaddr_in sin4;
  166. memset(&sin4,0,sizeof(sin4));
  167. sin4.sin_family = AF_INET;
  168. sin4.sin_port = htons(localTcpPort);
  169. sin4.sin_addr.s_addr = INADDR_ANY;
  170. if (::bind(_tcpV4ListenSocket,(const struct sockaddr *)&sin4,sizeof(sin4))) {
  171. _closeSockets();
  172. throw std::runtime_error("unable to bind to local TCP port");
  173. }
  174. if (::listen(_tcpV4ListenSocket,16)) {
  175. _closeSockets();
  176. throw std::runtime_error("listen() failed");
  177. }
  178. FD_SET(_tcpV4ListenSocket,&_readfds);
  179. }
  180. }
  181. if (localUdpPort > 0) {
  182. if (localUdpPort > 0xffff) {
  183. _closeSockets();
  184. throw std::runtime_error("invalid local UDP port number");
  185. }
  186. { // bind UDP IPv6
  187. #ifdef __WINDOWS__
  188. SOCKET s = ::socket(AF_INET6,SOCK_DGRAM,0);
  189. if (s == INVALID_SOCKET) {
  190. _closeSockets();
  191. throw std::runtime_error("unable to create IPv6 SOCK_DGRAM socket");
  192. }
  193. #else
  194. int s = ::socket(AF_INET6,SOCK_DGRAM,0);
  195. if (s <= 0) {
  196. _closeSockets();
  197. throw std::runtime_error("unable to create IPv6 SOCK_DGRAM socket");
  198. }
  199. #endif
  200. {
  201. #ifdef __WINDOWS__
  202. BOOL f;
  203. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  204. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  205. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  206. #else
  207. int f;
  208. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  209. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  210. #ifdef IP_DONTFRAG
  211. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  212. #endif
  213. #ifdef IP_MTU_DISCOVER
  214. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  215. #endif
  216. #ifdef IPV6_MTU_DISCOVER
  217. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  218. #endif
  219. #endif
  220. }
  221. struct sockaddr_in6 sin6;
  222. memset(&sin6,0,sizeof(sin6));
  223. sin6.sin6_family = AF_INET6;
  224. sin6.sin6_port = htons(localUdpPort);
  225. memcpy(&(sin6.sin6_addr),&in6addr_any,sizeof(struct in6_addr));
  226. if (::bind(s,(const struct sockaddr *)&sin6,sizeof(sin6))) {
  227. #ifdef __WINDOWS__
  228. ::closesocket(s);
  229. #else
  230. ::close(s);
  231. #endif
  232. _closeSockets();
  233. throw std::runtime_error("unable to bind to port");
  234. }
  235. FD_SET(s,&_readfds);
  236. _udpV6Socket = SharedPtr<Socket>(new UdpSocket(Socket::ZT_SOCKET_TYPE_UDP_V6,s));
  237. }
  238. { // bind UDP IPv4
  239. #ifdef __WINDOWS__
  240. SOCKET s = ::socket(AF_INET,SOCK_DGRAM,0);
  241. if (s == INVALID_SOCKET) {
  242. _closeSockets();
  243. throw std::runtime_error("unable to create IPv4 SOCK_DGRAM socket");
  244. }
  245. #else
  246. int s = ::socket(AF_INET,SOCK_DGRAM,0);
  247. if (s <= 0) {
  248. _closeSockets();
  249. throw std::runtime_error("unable to create IPv4 SOCK_DGRAM socket");
  250. }
  251. #endif
  252. {
  253. #ifdef __WINDOWS__
  254. BOOL f;
  255. f = FALSE; setsockopt(_sock,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  256. f = FALSE; setsockopt(_sock,IPPROTO_IP,IP_DONTFRAGMENT,(const char *)&f,sizeof(f));
  257. #else
  258. int f;
  259. f = 0; setsockopt(_sock,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  260. #ifdef IP_DONTFRAG
  261. f = 0; setsockopt(_sock,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  262. #endif
  263. #ifdef IP_MTU_DISCOVER
  264. f = 0; setsockopt(_sock,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  265. #endif
  266. #endif
  267. }
  268. struct sockaddr_in sin4;
  269. memset(&sin4,0,sizeof(sin4));
  270. sin4.sin_family = AF_INET;
  271. sin4.sin_port = htons(localUdpPort);
  272. sin4.sin_addr.s_addr = INADDR_ANY;
  273. if (::bind(s,(const struct sockaddr *)&sin4,sizeof(sin4))) {
  274. #ifdef __WINDOWS__
  275. ::closesocket(s);
  276. #else
  277. ::close(s);
  278. #endif
  279. throw std::runtime_error("unable to bind to port");
  280. }
  281. FD_SET(s,&_readfds);
  282. _udpV4Socket = SharedPtr<Socket>(new UdpSocket(Socket::ZT_SOCKET_TYPE_UDP_V4,s));
  283. }
  284. }
  285. }
  286. SocketManager::~SocketManager()
  287. {
  288. Mutex::Lock _l(_pollLock);
  289. _closeSockets();
  290. }
  291. bool SocketManager::send(const InetAddress &to,bool tcp,const void *msg,unsigned int msglen)
  292. {
  293. if (tcp) {
  294. } else if (to.isV4()) {
  295. if (_udpV4Socket)
  296. return _udpV4Socket->send(to,msg,msglen);
  297. } else if (to.isV6()) {
  298. if (_udpV6Socket)
  299. return _udpV6Socket->send(to,msg,msglen);
  300. }
  301. return false;
  302. }
  303. bool SocketManager::sendFirewallOpener(const InetAddress &to,int hopLimit)
  304. {
  305. if (to.isV4()) {
  306. if (_udpV4Socket)
  307. return _udpV4Socket->sendWithHopLimit(to,msg,msglen,hopLimit);
  308. } else if (to.isV6()) {
  309. if (_udpV6Socket)
  310. return _udpV6Socket->sendWithHopLimit(to,msg,msglen,hopLimit);
  311. }
  312. return false;
  313. }
  314. void SocketManager::poll(unsigned long timeout)
  315. {
  316. fd_set rfds,wfds,nfds;
  317. struct timeval tv;
  318. Mutex::Lock _l(_pollLock);
  319. _fdSetLock.lock();
  320. memcpy(&rfds,&_readfds,sizeof(rfds));
  321. memcpy(&wfds,&_writefds,sizeof(wfds));
  322. _fdSetLock.unlock();
  323. FD_ZERO(&nfds);
  324. tv.tv_sec = (long)(timeout / 1000);
  325. tv.tv_usec = (long)((timeout % 1000) * 1000);
  326. select(_nfds,&rfds,&wfds,&nfds,(timeout > 0) ? &tv : (struct timeval *)0);
  327. if (FD_ISSET(_whackReceivePipe,&rfds)) {
  328. char tmp[32];
  329. #ifdef __WINDOWS__
  330. ::recv(_whackReceivePipe,tmp,sizeof(tmp),0);
  331. #else
  332. ::read(_whackReceivePipe,tmp,sizeof(tmp));
  333. #endif
  334. }
  335. if ((_tcpV4ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV4ListenSocket,&rfds))) {
  336. }
  337. if ((_tcpV6ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV6ListenSocket,&rfds))) {
  338. }
  339. if ((_udpV4Socket)&&(FD_ISSET(_udpV4Socket->_sock,&rfds)))
  340. _udpV4Socket->notifyAvailableForRead(_udpV4Socket,this);
  341. if ((_udpV6Socket)&&(FD_ISSET(_udpV6Socket->_sock,&rfds)))
  342. _udpV6Socket->notifyAvailableForRead(_udpV6Socket,this);
  343. std::vector< SharedPtr<Socket> > ts;
  344. {
  345. Mutex::Lock _l2(_tcpSockets_m);
  346. if (_tcpSockets.size()) {
  347. ts.reserve(_tcpSockets.size());
  348. for(std::map< InetAddress,SharedPtr<Socket> >::iterator s(_tcpSockets.begin());s!=_tcpSockets.end();++s)
  349. ts.push_back(s->second);
  350. }
  351. }
  352. for(std::vector< SharedPtr<Socket> >::iterator s(ts.begin());s!=ts.end();++s) {
  353. if (FD_ISSET((*s)->_sock,&rfds))
  354. s->notifyAvailableForRead(*s,this);
  355. if (FD_ISSET((*s)->_sock,&wfds))
  356. s->notifyAvailableForWrite(*s,this);
  357. }
  358. }
  359. void SocketManager::whack()
  360. {
  361. _whackSendPipe_m.lock();
  362. #ifdef __WINDOWS__
  363. ::send(_whackSendPipe,(const void *)this,1,0);
  364. #else
  365. ::write(_whackSendPipe,(const void *)this,1); // data is arbitrary, just send a byte
  366. #endif
  367. _whackSendPipe_m.unlock();
  368. }
  369. } // namespace ZeroTier