SocketManager.cpp 13 KB

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