SocketManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 <unistd.h>
  38. #include <sys/socket.h>
  39. #include <arpa/inet.h>
  40. #include <signal.h>
  41. #endif
  42. // Allow us to use the same value on Windows and *nix
  43. #ifndef INVALID_SOCKET
  44. #define INVALID_SOCKET (-1)
  45. #endif
  46. namespace ZeroTier {
  47. #ifdef __WINDOWS__
  48. // hack from StackOverflow, behaves a bit like pipe() on *nix systems
  49. static inline void __winpipe(SOCKET fds[2])
  50. {
  51. struct sockaddr_in inaddr;
  52. struct sockaddr addr;
  53. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  54. memset(&inaddr, 0, sizeof(inaddr));
  55. memset(&addr, 0, sizeof(addr));
  56. inaddr.sin_family = AF_INET;
  57. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  58. inaddr.sin_port = 0;
  59. int yes=1;
  60. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  61. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  62. listen(lst,1);
  63. int len=sizeof(inaddr);
  64. getsockname(lst, &addr,&len);
  65. fds[0]=::socket(AF_INET, SOCK_STREAM,0);
  66. connect(fds[0],&addr,len);
  67. fds[1]=accept(lst,0,0);
  68. closesocket(lst);
  69. }
  70. #endif
  71. SocketManager::SocketManager(
  72. int localUdpPort,
  73. int localTcpPort,
  74. void (*packetHandler)(const SharedPtr<Socket> &,void *,const InetAddress &,Buffer<ZT_SOCKET_MAX_MESSAGE_LEN> &),
  75. void *arg) :
  76. _whackSendPipe(INVALID_SOCKET),
  77. _whackReceivePipe(INVALID_SOCKET),
  78. _tcpV4ListenSocket(INVALID_SOCKET),
  79. _tcpV6ListenSocket(INVALID_SOCKET),
  80. _nfds(0),
  81. _packetHandler(packetHandler),
  82. _arg(arg)
  83. {
  84. FD_ZERO(&_readfds);
  85. FD_ZERO(&_writefds);
  86. #ifdef __WINDOWS__
  87. {
  88. SOCKET tmps[2] = { INVALID_SOCKET,INVALID_SOCKET };
  89. __winpipe(tmps);
  90. _whackSendPipe = tmps[0];
  91. _whackReceivePipe = tmps[1];
  92. }
  93. #else
  94. {
  95. int tmpfds[2];
  96. if (::pipe(tmpfds))
  97. throw std::runtime_error("pipe() failed");
  98. _whackSendPipe = tmpfds[1];
  99. _whackReceivePipe = tmpfds[0];
  100. }
  101. #endif
  102. fcntl(_whackReceivePipe,F_SETFL,O_NONBLOCK);
  103. FD_SET(_whackReceivePipe,&_readfds);
  104. if (localTcpPort > 0) {
  105. if (localTcpPort > 0xffff) {
  106. _closeSockets();
  107. throw std::runtime_error("invalid local TCP port number");
  108. }
  109. { // bind TCP IPv6
  110. _tcpV6ListenSocket = ::socket(AF_INET6,SOCK_STREAM,0);
  111. #ifdef __WINDOWS__
  112. if (_tcpV6ListenSocket == INVALID_SOCKET) {
  113. _closeSockets();
  114. throw std::runtime_error("unable to create IPv6 SOCK_STREAM socket");
  115. }
  116. #else
  117. if (_tcpV6ListenSocket <= 0) {
  118. _closeSockets();
  119. throw std::runtime_error("unable to create IPv6 SOCK_STREAM socket");
  120. }
  121. #endif
  122. #ifdef __WINDOWS__
  123. {
  124. BOOL f;
  125. f = TRUE; ::setsockopt(_tcpV6ListenSocket,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  126. f = TRUE; ::setsockopt(_tcpV6ListenSocket,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  127. }
  128. #else
  129. {
  130. int f;
  131. f = 1; ::setsockopt(_tcpV6ListenSocket,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  132. f = 1; ::setsockopt(_tcpV6ListenSocket,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  133. }
  134. #endif
  135. fcntl(_tcpV6ListenSocket,F_SETFL,O_NONBLOCK);
  136. struct sockaddr_in6 sin6;
  137. memset(&sin6,0,sizeof(sin6));
  138. sin6.sin6_family = AF_INET6;
  139. sin6.sin6_port = htons(localTcpPort);
  140. memcpy(&(sin6.sin6_addr),&in6addr_any,sizeof(struct in6_addr));
  141. if (::bind(_tcpV6ListenSocket,(const struct sockaddr *)&sin6,sizeof(sin6))) {
  142. _closeSockets();
  143. throw std::runtime_error("unable to bind to local TCP port");
  144. }
  145. if (::listen(_tcpV6ListenSocket,16)) {
  146. _closeSockets();
  147. throw std::runtime_error("listen() failed");
  148. }
  149. FD_SET(_tcpV6ListenSocket,&_readfds);
  150. }
  151. { // bind TCP IPv4
  152. _tcpV4ListenSocket = ::socket(AF_INET,SOCK_STREAM,0);
  153. #ifdef __WINDOWS__
  154. if (_tcpV4ListenSocket == INVALID_SOCKET) {
  155. _closeSockets();
  156. throw std::runtime_error("unable to create IPv4 SOCK_STREAM socket");
  157. }
  158. #else
  159. if (_tcpV4ListenSocket <= 0) {
  160. _closeSockets();
  161. throw std::runtime_error("unable to create IPv4 SOCK_STREAM socket");
  162. }
  163. #endif
  164. #ifdef __WINDOWS__
  165. {
  166. BOOL f = TRUE; ::setsockopt(_tcpV4ListenSocket,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  167. }
  168. #else
  169. {
  170. int f = 1; ::setsockopt(_tcpV4ListenSocket,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  171. }
  172. #endif
  173. fcntl(_tcpV4ListenSocket,F_SETFL,O_NONBLOCK);
  174. struct sockaddr_in sin4;
  175. memset(&sin4,0,sizeof(sin4));
  176. sin4.sin_family = AF_INET;
  177. sin4.sin_port = htons(localTcpPort);
  178. sin4.sin_addr.s_addr = INADDR_ANY;
  179. if (::bind(_tcpV4ListenSocket,(const struct sockaddr *)&sin4,sizeof(sin4))) {
  180. _closeSockets();
  181. throw std::runtime_error("unable to bind to local TCP port");
  182. }
  183. if (::listen(_tcpV4ListenSocket,16)) {
  184. _closeSockets();
  185. throw std::runtime_error("listen() failed");
  186. }
  187. FD_SET(_tcpV4ListenSocket,&_readfds);
  188. }
  189. }
  190. if (localUdpPort > 0) {
  191. if (localUdpPort > 0xffff) {
  192. _closeSockets();
  193. throw std::runtime_error("invalid local UDP port number");
  194. }
  195. { // bind UDP IPv6
  196. #ifdef __WINDOWS__
  197. SOCKET s = ::socket(AF_INET6,SOCK_DGRAM,0);
  198. if (s == INVALID_SOCKET) {
  199. _closeSockets();
  200. throw std::runtime_error("unable to create IPv6 SOCK_DGRAM socket");
  201. }
  202. #else
  203. int s = ::socket(AF_INET6,SOCK_DGRAM,0);
  204. if (s <= 0) {
  205. _closeSockets();
  206. throw std::runtime_error("unable to create IPv6 SOCK_DGRAM socket");
  207. }
  208. #endif
  209. {
  210. #ifdef __WINDOWS__
  211. BOOL f;
  212. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  213. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  214. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  215. #else
  216. int f;
  217. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  218. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  219. #ifdef IP_DONTFRAG
  220. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  221. #endif
  222. #ifdef IP_MTU_DISCOVER
  223. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  224. #endif
  225. #ifdef IPV6_MTU_DISCOVER
  226. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  227. #endif
  228. #endif
  229. }
  230. struct sockaddr_in6 sin6;
  231. memset(&sin6,0,sizeof(sin6));
  232. sin6.sin6_family = AF_INET6;
  233. sin6.sin6_port = htons(localUdpPort);
  234. memcpy(&(sin6.sin6_addr),&in6addr_any,sizeof(struct in6_addr));
  235. if (::bind(s,(const struct sockaddr *)&sin6,sizeof(sin6))) {
  236. #ifdef __WINDOWS__
  237. ::closesocket(s);
  238. #else
  239. ::close(s);
  240. #endif
  241. _closeSockets();
  242. throw std::runtime_error("unable to bind to port");
  243. }
  244. _udpV6Socket = SharedPtr<Socket>(new UdpSocket(Socket::ZT_SOCKET_TYPE_UDP_V6,s));
  245. fcntl(s,F_SETFL,O_NONBLOCK);
  246. FD_SET(s,&_readfds);
  247. }
  248. { // bind UDP IPv4
  249. #ifdef __WINDOWS__
  250. SOCKET s = ::socket(AF_INET,SOCK_DGRAM,0);
  251. if (s == INVALID_SOCKET) {
  252. _closeSockets();
  253. throw std::runtime_error("unable to create IPv4 SOCK_DGRAM socket");
  254. }
  255. #else
  256. int s = ::socket(AF_INET,SOCK_DGRAM,0);
  257. if (s <= 0) {
  258. _closeSockets();
  259. throw std::runtime_error("unable to create IPv4 SOCK_DGRAM socket");
  260. }
  261. #endif
  262. {
  263. #ifdef __WINDOWS__
  264. BOOL f;
  265. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  266. f = FALSE; setsockopt(s,IPPROTO_IP,IP_DONTFRAGMENT,(const char *)&f,sizeof(f));
  267. #else
  268. int f;
  269. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  270. #ifdef IP_DONTFRAG
  271. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  272. #endif
  273. #ifdef IP_MTU_DISCOVER
  274. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  275. #endif
  276. #endif
  277. }
  278. struct sockaddr_in sin4;
  279. memset(&sin4,0,sizeof(sin4));
  280. sin4.sin_family = AF_INET;
  281. sin4.sin_port = htons(localUdpPort);
  282. sin4.sin_addr.s_addr = INADDR_ANY;
  283. if (::bind(s,(const struct sockaddr *)&sin4,sizeof(sin4))) {
  284. #ifdef __WINDOWS__
  285. ::closesocket(s);
  286. #else
  287. ::close(s);
  288. #endif
  289. throw std::runtime_error("unable to bind to port");
  290. }
  291. _udpV4Socket = SharedPtr<Socket>(new UdpSocket(Socket::ZT_SOCKET_TYPE_UDP_V4,s));
  292. fcntl(s,F_SETFL,O_NONBLOCK);
  293. FD_SET(s,&_readfds);
  294. }
  295. }
  296. _updateNfds();
  297. }
  298. SocketManager::~SocketManager()
  299. {
  300. Mutex::Lock _l(_pollLock);
  301. _closeSockets();
  302. }
  303. bool SocketManager::send(const InetAddress &to,bool tcp,const void *msg,unsigned int msglen)
  304. {
  305. if (tcp) {
  306. } else if (to.isV4()) {
  307. if (_udpV4Socket)
  308. return _udpV4Socket->send(to,msg,msglen);
  309. } else if (to.isV6()) {
  310. if (_udpV6Socket)
  311. return _udpV6Socket->send(to,msg,msglen);
  312. }
  313. return false;
  314. }
  315. bool SocketManager::sendFirewallOpener(const InetAddress &to,int hopLimit)
  316. {
  317. if (to.isV4()) {
  318. if (_udpV4Socket)
  319. return ((UdpSocket *)_udpV4Socket.ptr())->sendWithHopLimit(to,"",1,hopLimit);
  320. } else if (to.isV6()) {
  321. if (_udpV6Socket)
  322. return ((UdpSocket *)_udpV6Socket.ptr())->sendWithHopLimit(to,"",1,hopLimit);
  323. }
  324. return false;
  325. }
  326. void SocketManager::poll(unsigned long timeout)
  327. {
  328. fd_set rfds,wfds,efds;
  329. struct timeval tv;
  330. std::vector< SharedPtr<Socket> > ts;
  331. #ifdef __WINDOWS__
  332. SOCKET sockfd;
  333. #else
  334. int sockfd;
  335. #endif
  336. Mutex::Lock _l(_pollLock);
  337. _fdSetLock.lock();
  338. memcpy(&rfds,&_readfds,sizeof(rfds));
  339. memcpy(&wfds,&_writefds,sizeof(wfds));
  340. _fdSetLock.unlock();
  341. FD_ZERO(&efds);
  342. tv.tv_sec = (long)(timeout / 1000);
  343. tv.tv_usec = (long)((timeout % 1000) * 1000);
  344. select(_nfds + 1,&rfds,&wfds,&efds,(timeout > 0) ? &tv : (struct timeval *)0);
  345. if (FD_ISSET(_whackReceivePipe,&rfds)) {
  346. char tmp;
  347. #ifdef __WINDOWS__
  348. ::recv(_whackReceivePipe,&tmp,1,0);
  349. #else
  350. ::read(_whackReceivePipe,&tmp,1);
  351. #endif
  352. }
  353. if ((_tcpV4ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV4ListenSocket,&rfds))) {
  354. struct sockaddr_in from;
  355. socklen_t fromlen = sizeof(from);
  356. sockfd = accept(_tcpV4ListenSocket,(struct sockaddr *)&from,&fromlen);
  357. #ifdef __WINDOWS__
  358. if (sockfd != INVALID_SOCKET) {
  359. #else
  360. if (sockfd > 0) {
  361. #endif
  362. InetAddress fromia((const struct sockaddr *)&from);
  363. Mutex::Lock _l2(_tcpSockets_m);
  364. try {
  365. _tcpSockets[fromia] = SharedPtr<Socket>(new TcpSocket(this,sockfd,false,fromia));
  366. fcntl(sockfd,F_SETFL,O_NONBLOCK);
  367. _fdSetLock.lock();
  368. FD_SET(sockfd,&_readfds);
  369. _fdSetLock.unlock();
  370. if (sockfd > _nfds)
  371. _nfds = sockfd;
  372. } catch ( ... ) {
  373. ::close(sockfd);
  374. }
  375. }
  376. }
  377. if ((_tcpV6ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV6ListenSocket,&rfds))) {
  378. struct sockaddr_in6 from;
  379. socklen_t fromlen = sizeof(from);
  380. sockfd = accept(_tcpV6ListenSocket,(struct sockaddr *)&from,&fromlen);
  381. #ifdef __WINDOWS__
  382. if (sockfd != INVALID_SOCKET) {
  383. #else
  384. if (sockfd > 0) {
  385. #endif
  386. InetAddress fromia((const struct sockaddr *)&from);
  387. Mutex::Lock _l2(_tcpSockets_m);
  388. try {
  389. _tcpSockets[fromia] = SharedPtr<Socket>(new TcpSocket(this,sockfd,false,fromia));
  390. fcntl(sockfd,F_SETFL,O_NONBLOCK);
  391. _fdSetLock.lock();
  392. FD_SET(sockfd,&_readfds);
  393. _fdSetLock.unlock();
  394. if (sockfd > _nfds)
  395. _nfds = sockfd;
  396. } catch ( ... ) {
  397. ::close(sockfd);
  398. }
  399. }
  400. }
  401. if ((_udpV4Socket)&&(FD_ISSET(_udpV4Socket->_sock,&rfds))) {
  402. _udpV4Socket->notifyAvailableForRead(_udpV4Socket,this);
  403. }
  404. if ((_udpV6Socket)&&(FD_ISSET(_udpV6Socket->_sock,&rfds))) {
  405. _udpV6Socket->notifyAvailableForRead(_udpV6Socket,this);
  406. }
  407. bool closedSockets = false;
  408. { // grab copy of TCP sockets list because _tcpSockets[] might be changed in a handler
  409. Mutex::Lock _l2(_tcpSockets_m);
  410. if (_tcpSockets.size()) {
  411. ts.reserve(_tcpSockets.size());
  412. uint64_t now = Utils::now();
  413. for(std::map< InetAddress,SharedPtr<Socket> >::iterator s(_tcpSockets.begin());s!=_tcpSockets.end();) {
  414. if ((now - ((TcpSocket *)s->second.ptr())->_lastActivity) < ZT_TCP_TUNNEL_ACTIVITY_TIMEOUT) {
  415. ts.push_back(s->second);
  416. ++s;
  417. } else {
  418. _fdSetLock.lock();
  419. FD_CLR(s->second->_sock,&_readfds);
  420. FD_CLR(s->second->_sock,&_writefds);
  421. _fdSetLock.unlock();
  422. _tcpSockets.erase(s++);
  423. closedSockets = true;
  424. }
  425. }
  426. }
  427. }
  428. for(std::vector< SharedPtr<Socket> >::iterator s(ts.begin());s!=ts.end();++s) {
  429. if (FD_ISSET((*s)->_sock,&wfds)) {
  430. if (!(*s)->notifyAvailableForWrite(*s,this)) {
  431. {
  432. Mutex::Lock _l2(_tcpSockets_m);
  433. _tcpSockets.erase(((TcpSocket *)s->ptr())->_remote);
  434. }
  435. _fdSetLock.lock();
  436. FD_CLR((*s)->_sock,&_readfds);
  437. FD_CLR((*s)->_sock,&_writefds);
  438. _fdSetLock.unlock();
  439. closedSockets = true;
  440. continue;
  441. }
  442. }
  443. if (FD_ISSET((*s)->_sock,&rfds)) {
  444. if (!(*s)->notifyAvailableForRead(*s,this)) {
  445. {
  446. Mutex::Lock _l2(_tcpSockets_m);
  447. _tcpSockets.erase(((TcpSocket *)s->ptr())->_remote);
  448. }
  449. _fdSetLock.lock();
  450. FD_CLR((*s)->_sock,&_readfds);
  451. FD_CLR((*s)->_sock,&_writefds);
  452. _fdSetLock.unlock();
  453. closedSockets = true;
  454. continue;
  455. }
  456. }
  457. }
  458. if (closedSockets)
  459. _updateNfds();
  460. }
  461. void SocketManager::whack()
  462. {
  463. _whackSendPipe_m.lock();
  464. #ifdef __WINDOWS__
  465. ::send(_whackSendPipe,(const void *)this,1,0);
  466. #else
  467. ::write(_whackSendPipe,(const void *)this,1); // data is arbitrary, just send a byte
  468. #endif
  469. _whackSendPipe_m.unlock();
  470. }
  471. } // namespace ZeroTier