2
0

SocketManager.cpp 20 KB

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