SocketManager.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. }
  292. SocketManager::~SocketManager()
  293. {
  294. Mutex::Lock _l(_pollLock);
  295. _closeSockets();
  296. }
  297. bool SocketManager::send(const InetAddress &to,bool tcp,const void *msg,unsigned int msglen)
  298. {
  299. if (tcp) {
  300. } else if (to.isV4()) {
  301. if (_udpV4Socket)
  302. return _udpV4Socket->send(to,msg,msglen);
  303. } else if (to.isV6()) {
  304. if (_udpV6Socket)
  305. return _udpV6Socket->send(to,msg,msglen);
  306. }
  307. return false;
  308. }
  309. bool SocketManager::sendFirewallOpener(const InetAddress &to,int hopLimit)
  310. {
  311. if (to.isV4()) {
  312. if (_udpV4Socket)
  313. return ((UdpSocket *)_udpV4Socket.ptr())->sendWithHopLimit(to,"",1,hopLimit);
  314. } else if (to.isV6()) {
  315. if (_udpV6Socket)
  316. return ((UdpSocket *)_udpV6Socket.ptr())->sendWithHopLimit(to,"",1,hopLimit);
  317. }
  318. return false;
  319. }
  320. void SocketManager::poll(unsigned long timeout)
  321. {
  322. fd_set rfds,wfds,nfds;
  323. struct timeval tv;
  324. #ifdef __WINDOWS__
  325. SOCKET sockfd;
  326. #else
  327. int sockfd;
  328. #endif
  329. Mutex::Lock _l(_pollLock);
  330. _fdSetLock.lock();
  331. memcpy(&rfds,&_readfds,sizeof(rfds));
  332. memcpy(&wfds,&_writefds,sizeof(wfds));
  333. _fdSetLock.unlock();
  334. FD_ZERO(&nfds);
  335. tv.tv_sec = (long)(timeout / 1000);
  336. tv.tv_usec = (long)((timeout % 1000) * 1000);
  337. select(_nfds,&rfds,&wfds,&nfds,(timeout > 0) ? &tv : (struct timeval *)0);
  338. if (FD_ISSET(_whackReceivePipe,&rfds)) {
  339. char tmp[32];
  340. #ifdef __WINDOWS__
  341. ::recv(_whackReceivePipe,tmp,sizeof(tmp),0);
  342. #else
  343. ::read(_whackReceivePipe,tmp,sizeof(tmp));
  344. #endif
  345. }
  346. if ((_tcpV4ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV4ListenSocket,&rfds))) {
  347. struct sockaddr_in from;
  348. socklen_t fromlen = sizeof(from);
  349. sockfd = accept(_tcpV4ListenSocket,(struct sockaddr *)&from,&fromlen);
  350. #ifdef __WINDOWS__
  351. if (sockfd != INVALID_SOCKET) {
  352. #else
  353. if (sockfd > 0) {
  354. #endif
  355. InetAddress fromia((const struct sockaddr *)&from);
  356. Mutex::Lock _l2(_tcpSockets_m);
  357. _tcpSockets[fromia] = SharedPtr<Socket>(new TcpSocket(sockfd,false,fromia));
  358. _fdSetLock.lock();
  359. FD_SET(sockfd,&_readfds);
  360. _fdSetLock.unlock();
  361. }
  362. }
  363. if ((_tcpV6ListenSocket != INVALID_SOCKET)&&(FD_ISSET(_tcpV6ListenSocket,&rfds))) {
  364. struct sockaddr_in6 from;
  365. socklen_t fromlen = sizeof(from);
  366. sockfd = accept(_tcpV6ListenSocket,(struct sockaddr *)&from,&fromlen);
  367. #ifdef __WINDOWS__
  368. if (sockfd != INVALID_SOCKET) {
  369. #else
  370. if (sockfd > 0) {
  371. #endif
  372. InetAddress fromia((const struct sockaddr *)&from);
  373. Mutex::Lock _l2(_tcpSockets_m);
  374. _tcpSockets[fromia] = SharedPtr<Socket>(new TcpSocket(sockfd,false,fromia));
  375. _fdSetLock.lock();
  376. FD_SET(sockfd,&_readfds);
  377. _fdSetLock.unlock();
  378. }
  379. }
  380. if ((_udpV4Socket)&&(FD_ISSET(_udpV4Socket->_sock,&rfds)))
  381. _udpV4Socket->notifyAvailableForRead(_udpV4Socket,this);
  382. if ((_udpV6Socket)&&(FD_ISSET(_udpV6Socket->_sock,&rfds)))
  383. _udpV6Socket->notifyAvailableForRead(_udpV6Socket,this);
  384. std::vector< SharedPtr<Socket> > ts;
  385. {
  386. Mutex::Lock _l2(_tcpSockets_m);
  387. if (_tcpSockets.size()) {
  388. ts.reserve(_tcpSockets.size());
  389. for(std::map< InetAddress,SharedPtr<Socket> >::iterator s(_tcpSockets.begin());s!=_tcpSockets.end();) {
  390. if (true) { // TODO: TCP expiration check
  391. ts.push_back(s->second);
  392. ++s;
  393. } else _tcpSockets.erase(s++);
  394. }
  395. }
  396. }
  397. for(std::vector< SharedPtr<Socket> >::iterator s(ts.begin());s!=ts.end();++s) {
  398. if (FD_ISSET((*s)->_sock,&rfds))
  399. (*s)->notifyAvailableForRead(*s,this);
  400. if (FD_ISSET((*s)->_sock,&wfds))
  401. (*s)->notifyAvailableForWrite(*s,this);
  402. }
  403. }
  404. void SocketManager::whack()
  405. {
  406. _whackSendPipe_m.lock();
  407. #ifdef __WINDOWS__
  408. ::send(_whackSendPipe,(const void *)this,1,0);
  409. #else
  410. ::write(_whackSendPipe,(const void *)this,1); // data is arbitrary, just send a byte
  411. #endif
  412. _whackSendPipe_m.unlock();
  413. }
  414. } // namespace ZeroTier