SocketManager.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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. #include "UdpSocket.hpp"
  35. #include "TcpSocket.hpp"
  36. #ifndef __WINDOWS__
  37. #include <errno.h>
  38. #include <unistd.h>
  39. #include <sys/socket.h>
  40. #include <arpa/inet.h>
  41. #include <signal.h>
  42. #include <netinet/in.h>
  43. #include <netinet/tcp.h>
  44. #endif
  45. // Uncomment to turn off TCP Nagle
  46. //#define ZT_TCP_NODELAY
  47. // Allow us to use the same value on Windows and *nix
  48. #ifndef INVALID_SOCKET
  49. #define INVALID_SOCKET (-1)
  50. #endif
  51. #ifdef __WINDOWS__
  52. #define CLOSE_SOCKET(s) ::closesocket(s)
  53. #else
  54. #define CLOSE_SOCKET(s) ::close(s)
  55. #endif
  56. namespace ZeroTier {
  57. #ifdef __WINDOWS__
  58. // hack copied from StackOverflow, behaves a bit like pipe() on *nix systems
  59. static inline void winPipeHack(SOCKET fds[2])
  60. {
  61. struct sockaddr_in inaddr;
  62. struct sockaddr addr;
  63. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  64. memset(&inaddr, 0, sizeof(inaddr));
  65. memset(&addr, 0, sizeof(addr));
  66. inaddr.sin_family = AF_INET;
  67. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  68. inaddr.sin_port = 0;
  69. int yes=1;
  70. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  71. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  72. listen(lst,1);
  73. int len=sizeof(inaddr);
  74. getsockname(lst, &addr,&len);
  75. fds[0]=::socket(AF_INET, SOCK_STREAM,0);
  76. connect(fds[0],&addr,len);
  77. fds[1]=accept(lst,0,0);
  78. closesocket(lst);
  79. }
  80. #endif
  81. SocketManager::SocketManager(
  82. int localUdpPort,
  83. int localTcpPort,
  84. void (*packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &),
  85. void *arg) :
  86. _whackSendPipe(INVALID_SOCKET),
  87. _whackReceivePipe(INVALID_SOCKET),
  88. _tcpV4ListenSocket(INVALID_SOCKET),
  89. _tcpV6ListenSocket(INVALID_SOCKET),
  90. _nfds(0),
  91. _packetHandler(packetHandler),
  92. _arg(arg)
  93. {
  94. FD_ZERO(&_readfds);
  95. FD_ZERO(&_writefds);
  96. // Create a pipe or socket pair that can be used to interrupt select()
  97. #ifdef __WINDOWS__
  98. {
  99. SOCKET tmps[2] = { INVALID_SOCKET,INVALID_SOCKET };
  100. winPipeHack(tmps);
  101. _whackSendPipe = tmps[0];
  102. _whackReceivePipe = tmps[1];
  103. u_long iMode=1;
  104. ioctlsocket(tmps[1],FIONBIO,&iMode);
  105. }
  106. #else
  107. {
  108. int tmpfds[2];
  109. if (::pipe(tmpfds))
  110. throw std::runtime_error("pipe() failed");
  111. _whackSendPipe = tmpfds[1];
  112. _whackReceivePipe = tmpfds[0];
  113. fcntl(_whackReceivePipe,F_SETFL,O_NONBLOCK);
  114. }
  115. #endif
  116. FD_SET(_whackReceivePipe,&_readfds);
  117. if (localTcpPort > 0) {
  118. if (localTcpPort > 0xffff) {
  119. _closeSockets();
  120. throw std::runtime_error("invalid local TCP port number");
  121. }
  122. { // bind TCP IPv6
  123. _tcpV6ListenSocket = ::socket(AF_INET6,SOCK_STREAM,0);
  124. #ifdef __WINDOWS__
  125. if (_tcpV6ListenSocket != INVALID_SOCKET) {
  126. {
  127. BOOL f;
  128. f = TRUE; ::setsockopt(_tcpV6ListenSocket,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  129. f = TRUE; ::setsockopt(_tcpV6ListenSocket,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  130. u_long iMode=1;
  131. ioctlsocket(_tcpV6ListenSocket,FIONBIO,&iMode);
  132. }
  133. #else
  134. if (_tcpV6ListenSocket > 0) {
  135. {
  136. int f;
  137. f = 1; ::setsockopt(_tcpV6ListenSocket,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  138. f = 1; ::setsockopt(_tcpV6ListenSocket,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  139. fcntl(_tcpV6ListenSocket,F_SETFL,O_NONBLOCK);
  140. }
  141. #endif // __WINDOWS__ / not __WINDOWS__
  142. struct sockaddr_in6 sin6;
  143. memset(&sin6,0,sizeof(sin6));
  144. sin6.sin6_family = AF_INET6;
  145. sin6.sin6_port = htons(localTcpPort);
  146. memcpy(&(sin6.sin6_addr),&in6addr_any,sizeof(struct in6_addr));
  147. if (::bind(_tcpV6ListenSocket,(const struct sockaddr *)&sin6,sizeof(sin6))) {
  148. _closeSockets();
  149. throw std::runtime_error("unable to bind to local TCP port");
  150. }
  151. if (::listen(_tcpV6ListenSocket,16)) {
  152. _closeSockets();
  153. throw std::runtime_error("listen() failed");
  154. }
  155. FD_SET(_tcpV6ListenSocket,&_readfds);
  156. }
  157. }
  158. { // bind TCP IPv4
  159. _tcpV4ListenSocket = ::socket(AF_INET,SOCK_STREAM,0);
  160. #ifdef __WINDOWS__
  161. if (_tcpV4ListenSocket == INVALID_SOCKET) {
  162. #else
  163. if (_tcpV4ListenSocket <= 0) {
  164. #endif
  165. _closeSockets();
  166. throw std::runtime_error("unable to create IPv4 SOCK_STREAM socket");
  167. }
  168. #ifdef __WINDOWS__
  169. {
  170. BOOL f = TRUE; ::setsockopt(_tcpV4ListenSocket,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  171. u_long iMode=1;
  172. ioctlsocket(_tcpV4ListenSocket,FIONBIO,&iMode);
  173. }
  174. #else
  175. {
  176. int f = 1; ::setsockopt(_tcpV4ListenSocket,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  177. fcntl(_tcpV4ListenSocket,F_SETFL,O_NONBLOCK);
  178. }
  179. #endif
  180. struct sockaddr_in sin4;
  181. memset(&sin4,0,sizeof(sin4));
  182. sin4.sin_family = AF_INET;
  183. sin4.sin_port = htons(localTcpPort);
  184. sin4.sin_addr.s_addr = INADDR_ANY;
  185. if (::bind(_tcpV4ListenSocket,(const struct sockaddr *)&sin4,sizeof(sin4))) {
  186. _closeSockets();
  187. throw std::runtime_error("unable to bind to local TCP port");
  188. }
  189. if (::listen(_tcpV4ListenSocket,16)) {
  190. _closeSockets();
  191. throw std::runtime_error("listen() failed");
  192. }
  193. FD_SET(_tcpV4ListenSocket,&_readfds);
  194. }
  195. }
  196. if (localUdpPort > 0) {
  197. if (localUdpPort > 0xffff) {
  198. _closeSockets();
  199. throw std::runtime_error("invalid local UDP port number");
  200. }
  201. { // bind UDP IPv6
  202. #ifdef __WINDOWS__
  203. SOCKET s = ::socket(AF_INET6,SOCK_DGRAM,0);
  204. if (s != INVALID_SOCKET) {
  205. #else
  206. int s = ::socket(AF_INET6,SOCK_DGRAM,0);
  207. if (s > 0) {
  208. #endif
  209. {
  210. int bs = 1048576;
  211. while (bs >= 65536) {
  212. int tmpbs = bs;
  213. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  214. break;
  215. bs -= 16384;
  216. }
  217. bs = 1048576;
  218. while (bs >= 65536) {
  219. int tmpbs = bs;
  220. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  221. break;
  222. bs -= 16384;
  223. }
  224. #ifdef __WINDOWS__
  225. BOOL f;
  226. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  227. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  228. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  229. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  230. #else
  231. int f;
  232. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  233. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  234. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  235. #ifdef IP_DONTFRAG
  236. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  237. #endif
  238. #ifdef IP_MTU_DISCOVER
  239. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  240. #endif
  241. #ifdef IPV6_MTU_DISCOVER
  242. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  243. #endif
  244. #endif
  245. }
  246. struct sockaddr_in6 sin6;
  247. memset(&sin6,0,sizeof(sin6));
  248. sin6.sin6_family = AF_INET6;
  249. sin6.sin6_port = htons(localUdpPort);
  250. memcpy(&(sin6.sin6_addr),&in6addr_any,sizeof(struct in6_addr));
  251. if (::bind(s,(const struct sockaddr *)&sin6,sizeof(sin6))) {
  252. CLOSE_SOCKET(s);
  253. _closeSockets();
  254. throw std::runtime_error("unable to bind to port");
  255. }
  256. _udpV6Socket = SharedPtr<Socket>(new UdpSocket(Socket::ZT_SOCKET_TYPE_UDP_V6,s));
  257. #ifdef __WINDOWS__
  258. u_long iMode=1;
  259. ioctlsocket(s,FIONBIO,&iMode);
  260. #else
  261. fcntl(s,F_SETFL,O_NONBLOCK);
  262. #endif
  263. FD_SET(s,&_readfds);
  264. }
  265. }
  266. { // bind UDP IPv4
  267. #ifdef __WINDOWS__
  268. SOCKET s = ::socket(AF_INET,SOCK_DGRAM,0);
  269. if (s == INVALID_SOCKET) {
  270. _closeSockets();
  271. throw std::runtime_error("unable to create IPv4 SOCK_DGRAM socket");
  272. }
  273. #else
  274. int s = ::socket(AF_INET,SOCK_DGRAM,0);
  275. if (s <= 0) {
  276. _closeSockets();
  277. throw std::runtime_error("unable to create IPv4 SOCK_DGRAM socket");
  278. }
  279. #endif
  280. {
  281. int bs = 1048576;
  282. while (bs >= 65536) {
  283. int tmpbs = bs;
  284. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  285. break;
  286. bs -= 16384;
  287. }
  288. bs = 1048576;
  289. while (bs >= 65536) {
  290. int tmpbs = bs;
  291. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  292. break;
  293. bs -= 16384;
  294. }
  295. #ifdef __WINDOWS__
  296. BOOL f;
  297. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  298. f = FALSE; setsockopt(s,IPPROTO_IP,IP_DONTFRAGMENT,(const char *)&f,sizeof(f));
  299. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  300. #else
  301. int f;
  302. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  303. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  304. #ifdef IP_DONTFRAG
  305. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  306. #endif
  307. #ifdef IP_MTU_DISCOVER
  308. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  309. #endif
  310. #endif
  311. }
  312. struct sockaddr_in sin4;
  313. memset(&sin4,0,sizeof(sin4));
  314. sin4.sin_family = AF_INET;
  315. sin4.sin_port = htons(localUdpPort);
  316. sin4.sin_addr.s_addr = INADDR_ANY;
  317. if (::bind(s,(const struct sockaddr *)&sin4,sizeof(sin4))) {
  318. CLOSE_SOCKET(s);
  319. _closeSockets();
  320. throw std::runtime_error("unable to bind to port");
  321. }
  322. _udpV4Socket = SharedPtr<Socket>(new UdpSocket(Socket::ZT_SOCKET_TYPE_UDP_V4,s));
  323. #ifdef __WINDOWS__
  324. u_long iMode=1;
  325. ioctlsocket(s,FIONBIO,&iMode);
  326. #else
  327. fcntl(s,F_SETFL,O_NONBLOCK);
  328. #endif
  329. FD_SET(s,&_readfds);
  330. }
  331. }
  332. _updateNfds();
  333. }
  334. SocketManager::~SocketManager()
  335. {
  336. Mutex::Lock _l(_pollLock);
  337. _closeSockets();
  338. }
  339. bool SocketManager::send(const InetAddress &to,bool tcp,bool autoConnectTcp,const void *msg,unsigned int msglen)
  340. {
  341. if (tcp) {
  342. SharedPtr<Socket> ts;
  343. {
  344. Mutex::Lock _l(_tcpSockets_m);
  345. std::map< InetAddress,SharedPtr<Socket> >::iterator opents(_tcpSockets.find(to));
  346. if (opents != _tcpSockets.end())
  347. ts = opents->second;
  348. }
  349. if (ts)
  350. return ts->send(to,msg,msglen);
  351. if (!autoConnectTcp)
  352. return false;
  353. #ifdef __WINDOWS__
  354. SOCKET s = ::socket(to.isV4() ? AF_INET : AF_INET6,SOCK_STREAM,0);
  355. if (s == INVALID_SOCKET)
  356. return false;
  357. { u_long iMode=1; ioctlsocket(s,FIONBIO,&iMode); }
  358. #ifdef ZT_TCP_NODELAY
  359. { BOOL f = TRUE; setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  360. #endif
  361. #else
  362. int s = ::socket(to.isV4() ? AF_INET : AF_INET6,SOCK_STREAM,0);
  363. if (s <= 0)
  364. return false;
  365. if (s >= FD_SETSIZE) {
  366. ::close(s);
  367. return false;
  368. }
  369. fcntl(s,F_SETFL,O_NONBLOCK);
  370. #ifdef ZT_TCP_NODELAY
  371. { int f = 1; setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  372. #endif
  373. #endif
  374. bool connecting = false;
  375. if (::connect(s,to.saddr(),to.saddrLen())) {
  376. #ifdef __WINDOWS__
  377. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  378. #else
  379. if (errno != EINPROGRESS) {
  380. #endif
  381. CLOSE_SOCKET(s);
  382. return false;
  383. } else connecting = true;
  384. }
  385. ts = SharedPtr<Socket>(new TcpSocket(this,s,Socket::ZT_SOCKET_TYPE_TCP_OUT,connecting,to));
  386. if (!ts->send(to,msg,msglen)) {
  387. _fdSetLock.lock();
  388. FD_CLR(s,&_readfds);
  389. FD_CLR(s,&_writefds);
  390. _fdSetLock.unlock();
  391. return false;
  392. }
  393. {
  394. Mutex::Lock _l(_tcpSockets_m);
  395. _tcpSockets[to] = ts;
  396. }
  397. _fdSetLock.lock();
  398. FD_SET(s,&_readfds);
  399. if (connecting)
  400. FD_SET(s,&_writefds);
  401. _fdSetLock.unlock();
  402. _updateNfds();
  403. whack();
  404. return true;
  405. } else if (to.isV4()) {
  406. if (_udpV4Socket)
  407. return _udpV4Socket->send(to,msg,msglen);
  408. } else if (to.isV6()) {
  409. if (_udpV6Socket)
  410. return _udpV6Socket->send(to,msg,msglen);
  411. }
  412. return false;
  413. }
  414. #ifdef ZT_FIREWALL_OPENER_DELAY
  415. bool SocketManager::sendFirewallOpener(const InetAddress &to,int hopLimit)
  416. {
  417. if (to.isV4()) {
  418. if (_udpV4Socket)
  419. return ((UdpSocket *)_udpV4Socket.ptr())->sendWithHopLimit(to,"",1,hopLimit);
  420. } else if (to.isV6()) {
  421. if (_udpV6Socket)
  422. return ((UdpSocket *)_udpV6Socket.ptr())->sendWithHopLimit(to,"",1,hopLimit);
  423. }
  424. return false;
  425. }
  426. #endif
  427. void SocketManager::poll(unsigned long timeout)
  428. {
  429. fd_set rfds,wfds,efds;
  430. struct timeval tv;
  431. std::vector< SharedPtr<Socket> > ts;
  432. #ifdef __WINDOWS__
  433. SOCKET sockfd;
  434. #else
  435. int sockfd;
  436. #endif
  437. Mutex::Lock _l(_pollLock);
  438. _fdSetLock.lock();
  439. memcpy(&rfds,&_readfds,sizeof(rfds));
  440. memcpy(&wfds,&_writefds,sizeof(wfds));
  441. _fdSetLock.unlock();
  442. FD_ZERO(&efds);
  443. #ifdef __WINDOWS__
  444. // Windows signals failed connects in exceptfds
  445. {
  446. Mutex::Lock _l2(_tcpSockets_m);
  447. for(std::map< InetAddress,SharedPtr<Socket> >::iterator s(_tcpSockets.begin());s!=_tcpSockets.end();++s) {
  448. if (((TcpSocket *)s->second.ptr())->_connecting)
  449. FD_SET(s->second->_sock,&efds);
  450. }
  451. }
  452. #endif
  453. tv.tv_sec = (long)(timeout / 1000);
  454. tv.tv_usec = (long)((timeout % 1000) * 1000);
  455. select(_nfds + 1,&rfds,&wfds,&efds,(timeout > 0) ? &tv : (struct timeval *)0);
  456. if (FD_ISSET(_whackReceivePipe,&rfds)) {
  457. char tmp[16];
  458. #ifdef __WINDOWS__
  459. ::recv(_whackReceivePipe,tmp,16,0);
  460. #else
  461. ::read(_whackReceivePipe,tmp,16);
  462. #endif
  463. }
  464. if ((_tcpV4ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV4ListenSocket,&rfds))) {
  465. struct sockaddr_in from;
  466. socklen_t fromlen = sizeof(from);
  467. sockfd = accept(_tcpV4ListenSocket,(struct sockaddr *)&from,&fromlen);
  468. #ifdef __WINDOWS__
  469. if (sockfd != INVALID_SOCKET) {
  470. #else
  471. if (sockfd > 0) {
  472. if (sockfd < FD_SETSIZE) {
  473. #endif
  474. InetAddress fromia((const struct sockaddr *)&from);
  475. Mutex::Lock _l2(_tcpSockets_m);
  476. try {
  477. _tcpSockets[fromia] = SharedPtr<Socket>(new TcpSocket(this,sockfd,Socket::ZT_SOCKET_TYPE_TCP_IN,false,fromia));
  478. #ifdef __WINDOWS__
  479. { u_long iMode=1; ioctlsocket(sockfd,FIONBIO,&iMode); }
  480. #ifdef ZT_TCP_NODELAY
  481. { BOOL f = TRUE; setsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  482. #endif
  483. #else
  484. fcntl(sockfd,F_SETFL,O_NONBLOCK);
  485. #ifdef ZT_TCP_NODELAY
  486. { int f = 1; setsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  487. #endif
  488. #endif
  489. _fdSetLock.lock();
  490. FD_SET(sockfd,&_readfds);
  491. _fdSetLock.unlock();
  492. if ((int)sockfd > (int)_nfds)
  493. _nfds = (int)sockfd;
  494. } catch ( ... ) {
  495. CLOSE_SOCKET(sockfd);
  496. }
  497. #ifndef __WINDOWS__
  498. } else {
  499. CLOSE_SOCKET(sockfd);
  500. }
  501. #endif
  502. }
  503. }
  504. if ((_tcpV6ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV6ListenSocket,&rfds))) {
  505. struct sockaddr_in6 from;
  506. socklen_t fromlen = sizeof(from);
  507. sockfd = accept(_tcpV6ListenSocket,(struct sockaddr *)&from,&fromlen);
  508. #ifdef __WINDOWS__
  509. if (sockfd != INVALID_SOCKET) {
  510. #else
  511. if (sockfd > 0) {
  512. if (sockfd < FD_SETSIZE) {
  513. #endif
  514. InetAddress fromia((const struct sockaddr *)&from);
  515. Mutex::Lock _l2(_tcpSockets_m);
  516. try {
  517. _tcpSockets[fromia] = SharedPtr<Socket>(new TcpSocket(this,sockfd,Socket::ZT_SOCKET_TYPE_TCP_IN,false,fromia));
  518. #ifdef __WINDOWS__
  519. { u_long iMode=1; ioctlsocket(sockfd,FIONBIO,&iMode); }
  520. #ifdef ZT_TCP_NODELAY
  521. { BOOL f = TRUE; setsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  522. #endif
  523. #else
  524. fcntl(sockfd,F_SETFL,O_NONBLOCK);
  525. #ifdef ZT_TCP_NODELAY
  526. { int f = 1; setsockopt(sockfd,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  527. #endif
  528. #endif
  529. _fdSetLock.lock();
  530. FD_SET(sockfd,&_readfds);
  531. _fdSetLock.unlock();
  532. if ((int)sockfd > (int)_nfds)
  533. _nfds = (int)sockfd;
  534. } catch ( ... ) {
  535. CLOSE_SOCKET(sockfd);
  536. }
  537. #ifndef __WINDOWS__
  538. } else {
  539. CLOSE_SOCKET(sockfd);
  540. }
  541. #endif
  542. }
  543. }
  544. if ((_udpV4Socket)&&(FD_ISSET(_udpV4Socket->_sock,&rfds))) {
  545. _udpV4Socket->notifyAvailableForRead(_udpV4Socket,this);
  546. }
  547. if ((_udpV6Socket)&&(FD_ISSET(_udpV6Socket->_sock,&rfds))) {
  548. _udpV6Socket->notifyAvailableForRead(_udpV6Socket,this);
  549. }
  550. bool closedSockets = false;
  551. { // grab copy of TCP sockets list because _tcpSockets[] might be changed in a handler
  552. Mutex::Lock _l2(_tcpSockets_m);
  553. if (!_tcpSockets.empty()) {
  554. ts.reserve(_tcpSockets.size());
  555. uint64_t now = Utils::now();
  556. for(std::map< InetAddress,SharedPtr<Socket> >::iterator s(_tcpSockets.begin());s!=_tcpSockets.end();) {
  557. #ifdef __WINDOWS__
  558. if ( ((now - ((TcpSocket *)s->second.ptr())->_lastActivity) < ZT_TCP_TUNNEL_ACTIVITY_TIMEOUT) && (! ((((TcpSocket *)s->second.ptr())->_connecting)&&(FD_ISSET(s->second->_sock,&efds))) ) ) {
  559. #else
  560. if ((now - ((TcpSocket *)s->second.ptr())->_lastActivity) < ZT_TCP_TUNNEL_ACTIVITY_TIMEOUT) {
  561. #endif
  562. ts.push_back(s->second);
  563. ++s;
  564. } else {
  565. _fdSetLock.lock();
  566. FD_CLR(s->second->_sock,&_readfds);
  567. FD_CLR(s->second->_sock,&_writefds);
  568. _fdSetLock.unlock();
  569. _tcpSockets.erase(s++);
  570. closedSockets = true;
  571. }
  572. }
  573. }
  574. }
  575. for(std::vector< SharedPtr<Socket> >::iterator s(ts.begin());s!=ts.end();++s) {
  576. if (FD_ISSET((*s)->_sock,&wfds)) {
  577. if (!(*s)->notifyAvailableForWrite(*s,this)) {
  578. {
  579. Mutex::Lock _l2(_tcpSockets_m);
  580. _tcpSockets.erase(((TcpSocket *)s->ptr())->_remote);
  581. }
  582. _fdSetLock.lock();
  583. FD_CLR((*s)->_sock,&_readfds);
  584. FD_CLR((*s)->_sock,&_writefds);
  585. _fdSetLock.unlock();
  586. closedSockets = true;
  587. continue;
  588. }
  589. }
  590. if (FD_ISSET((*s)->_sock,&rfds)) {
  591. if (!(*s)->notifyAvailableForRead(*s,this)) {
  592. {
  593. Mutex::Lock _l2(_tcpSockets_m);
  594. _tcpSockets.erase(((TcpSocket *)s->ptr())->_remote);
  595. }
  596. _fdSetLock.lock();
  597. FD_CLR((*s)->_sock,&_readfds);
  598. FD_CLR((*s)->_sock,&_writefds);
  599. _fdSetLock.unlock();
  600. closedSockets = true;
  601. continue;
  602. }
  603. }
  604. }
  605. if (closedSockets)
  606. _updateNfds();
  607. }
  608. void SocketManager::whack()
  609. {
  610. _whackSendPipe_m.lock();
  611. #ifdef __WINDOWS__
  612. ::send(_whackSendPipe,(const char *)this,1,0);
  613. #else
  614. ::write(_whackSendPipe,(const void *)this,1); // data is arbitrary, just send a byte
  615. #endif
  616. _whackSendPipe_m.unlock();
  617. }
  618. void SocketManager::closeTcpSockets()
  619. {
  620. {
  621. Mutex::Lock _l2(_tcpSockets_m);
  622. _fdSetLock.lock();
  623. for(std::map< InetAddress,SharedPtr<Socket> >::iterator s(_tcpSockets.begin());s!=_tcpSockets.end();++s) {
  624. FD_CLR(s->second->_sock,&_readfds);
  625. FD_CLR(s->second->_sock,&_writefds);
  626. }
  627. _fdSetLock.unlock();
  628. _tcpSockets.clear();
  629. }
  630. _updateNfds();
  631. }
  632. void SocketManager::_closeSockets()
  633. throw()
  634. {
  635. #ifdef __WINDOWS__
  636. if (_whackSendPipe != INVALID_SOCKET)
  637. ::closesocket(_whackSendPipe);
  638. if (_whackReceivePipe != INVALID_SOCKET)
  639. ::closesocket(_whackReceivePipe);
  640. if (_tcpV4ListenSocket != INVALID_SOCKET)
  641. ::closesocket(_tcpV4ListenSocket);
  642. if (_tcpV6ListenSocket != INVALID_SOCKET)
  643. ::closesocket(_tcpV6ListenSocket);
  644. #else
  645. if (_whackSendPipe > 0)
  646. ::close(_whackSendPipe);
  647. if (_whackReceivePipe > 0)
  648. ::close(_whackReceivePipe);
  649. if (_tcpV4ListenSocket > 0)
  650. ::close(_tcpV4ListenSocket);
  651. if (_tcpV4ListenSocket > 0)
  652. ::close(_tcpV6ListenSocket);
  653. #endif
  654. }
  655. void SocketManager::_updateNfds()
  656. {
  657. #ifdef __WINDOWS__
  658. SOCKET nfds = _whackSendPipe;
  659. #else
  660. int nfds = _whackSendPipe;
  661. #endif
  662. if (_whackReceivePipe > nfds)
  663. nfds = _whackReceivePipe;
  664. if (_tcpV4ListenSocket > nfds)
  665. nfds = _tcpV4ListenSocket;
  666. if (_tcpV6ListenSocket > nfds)
  667. nfds = _tcpV6ListenSocket;
  668. if ((_udpV4Socket)&&(_udpV4Socket->_sock > nfds))
  669. nfds = _udpV4Socket->_sock;
  670. if ((_udpV6Socket)&&(_udpV6Socket->_sock > nfds))
  671. nfds = _udpV6Socket->_sock;
  672. Mutex::Lock _l(_tcpSockets_m);
  673. for(std::map< InetAddress,SharedPtr<Socket> >::const_iterator s(_tcpSockets.begin());s!=_tcpSockets.end();++s) {
  674. if (s->second->_sock > nfds)
  675. nfds = s->second->_sock;
  676. }
  677. _nfds = (int)nfds;
  678. }
  679. } // namespace ZeroTier