Phy.hpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. #ifndef ZT_PHY_HPP
  28. #define ZT_PHY_HPP
  29. #include <stdio.h>
  30. #include <stdlib.h>
  31. #include <string.h>
  32. #include <list>
  33. #if defined(_WIN32) || defined(_WIN64)
  34. #include <WinSock2.h>
  35. #include <WS2tcpip.h>
  36. #include <Windows.h>
  37. #define ZT_PHY_SOCKFD_TYPE SOCKET
  38. #define ZT_PHY_SOCKFD_NULL (INVALID_SOCKET)
  39. #define ZT_PHY_SOCKFD_VALID(s) ((s) != INVALID_SOCKET)
  40. #define ZT_PHY_CLOSE_SOCKET(s) ::closesocket(s)
  41. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  42. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  43. #else // not Windows
  44. #include <errno.h>
  45. #include <signal.h>
  46. #include <unistd.h>
  47. #include <fcntl.h>
  48. #include <sys/time.h>
  49. #include <sys/types.h>
  50. #include <sys/select.h>
  51. #include <sys/socket.h>
  52. #include <arpa/inet.h>
  53. #include <netinet/in.h>
  54. #include <netinet/tcp.h>
  55. #define ZT_PHY_SOCKFD_TYPE int
  56. #define ZT_PHY_SOCKFD_NULL (-1)
  57. #define ZT_PHY_SOCKFD_VALID(s) ((s) > -1)
  58. #define ZT_PHY_CLOSE_SOCKET(s) ::close(s)
  59. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  60. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  61. #endif // Windows or not
  62. namespace ZeroTier {
  63. /**
  64. * Opaque socket type
  65. */
  66. typedef void PhySocket;
  67. /**
  68. * Simple templated non-blocking sockets implementation
  69. *
  70. * Yes there is boost::asio and libuv, but I like small binaries and I hate
  71. * build dependencies. Both drag in a whole bunch of pasta with them.
  72. *
  73. * This class is templated on a pointer to a handler class which must
  74. * implement the following functions:
  75. *
  76. * phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *from,void *data,unsigned long len)
  77. * phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  78. * phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  79. * phyOnTcpClose(PhySocket *sock,void **uptr)
  80. * phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  81. * phyOnTcpWritable(PhySocket *sock,void **uptr)
  82. *
  83. * These templates typically refer to function objects. Templates are used to
  84. * avoid the call overhead of indirection, which is surprisingly high for high
  85. * bandwidth applications pushing a lot of packets.
  86. *
  87. * The 'sock' pointer above is an opaque pointer to a socket. Each socket
  88. * has a 'uptr' user-settable/modifiable pointer associated with it, which
  89. * can be set on bind/connect calls and is passed as a void ** to permit
  90. * resetting at any time. The ACCEPT handler takes two sets of sock and
  91. * uptr: sockL and uptrL for the listen socket, and sockN and uptrN for
  92. * the new TCP connection socket that has just been created.
  93. *
  94. * Handlers are always called. On outgoing TCP connection, CONNECT is always
  95. * called on either success or failure followed by DATA and/or WRITABLE as
  96. * indicated. On socket close, handlers are called unless close() is told
  97. * explicitly not to call handlers. It is safe to close a socket within a
  98. * handler, and in that case close() can be told not to call handlers to
  99. * prevent recursion.
  100. *
  101. * This isn't thread-safe with the exception of whack(), which is safe to
  102. * call from another thread to abort poll().
  103. */
  104. template <typename HANDLER_PTR_TYPE>
  105. class Phy
  106. {
  107. private:
  108. HANDLER_PTR_TYPE _handler;
  109. enum PhySocketType
  110. {
  111. ZT_PHY_SOCKET_TCP_OUT_PENDING = 0x00,
  112. ZT_PHY_SOCKET_TCP_OUT_CONNECTED = 0x01,
  113. ZT_PHY_SOCKET_TCP_IN = 0x02,
  114. ZT_PHY_SOCKET_TCP_LISTEN = 0x03,
  115. ZT_PHY_SOCKET_RAW = 0x04,
  116. ZT_PHY_SOCKET_UDP = 0x05
  117. };
  118. struct PhySocketImpl
  119. {
  120. PhySocketType type;
  121. ZT_PHY_SOCKFD_TYPE sock;
  122. void *uptr; // user-settable pointer
  123. ZT_PHY_SOCKADDR_STORAGE_TYPE saddr; // remote for TCP_OUT and TCP_IN, local for TCP_LISTEN, RAW, and UDP
  124. };
  125. std::list<PhySocketImpl> _socks;
  126. fd_set _readfds;
  127. fd_set _writefds;
  128. #if defined(_WIN32) || defined(_WIN64)
  129. fd_set _exceptfds;
  130. #endif
  131. long _nfds;
  132. ZT_PHY_SOCKFD_TYPE _whackReceiveSocket;
  133. ZT_PHY_SOCKFD_TYPE _whackSendSocket;
  134. bool _noDelay;
  135. public:
  136. /**
  137. * @param handler Pointer of type HANDLER_PTR_TYPE to handler
  138. * @param noDelay If true, disable TCP NAGLE algorithm on TCP sockets
  139. */
  140. Phy(HANDLER_PTR_TYPE handler,bool noDelay) :
  141. _handler(handler)
  142. {
  143. FD_ZERO(&_readfds);
  144. FD_ZERO(&_writefds);
  145. #if defined(_WIN32) || defined(_WIN64)
  146. FD_ZERO(&_exceptfds);
  147. SOCKET pipes[2];
  148. { // hack copied from StackOverflow, behaves a bit like pipe() on *nix systems
  149. struct sockaddr_in inaddr;
  150. struct sockaddr addr;
  151. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  152. if (lst == INVALID_SOCKET)
  153. throw std::runtime_error("unable to create pipes for select() abort");
  154. memset(&inaddr, 0, sizeof(inaddr));
  155. memset(&addr, 0, sizeof(addr));
  156. inaddr.sin_family = AF_INET;
  157. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  158. inaddr.sin_port = 0;
  159. int yes=1;
  160. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  161. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  162. listen(lst,1);
  163. int len=sizeof(inaddr);
  164. getsockname(lst, &addr,&len);
  165. pipes[0]=::socket(AF_INET, SOCK_STREAM,0);
  166. if (pipes[0] == INVALID_SOCKET)
  167. throw std::runtime_error("unable to create pipes for select() abort");
  168. connect(pipes[0],&addr,len);
  169. pipes[1]=accept(lst,0,0);
  170. closesocket(lst);
  171. }
  172. #else // not Windows
  173. int pipes[2];
  174. if (::pipe(pipes))
  175. throw std::runtime_error("unable to create pipes for select() abort");
  176. #endif // Windows or not
  177. _nfds = (pipes[0] > pipes[1]) ? (long)pipes[0] : (long)pipes[1];
  178. _whackReceiveSocket = pipes[0];
  179. _whackSendSocket = pipes[1];
  180. _noDelay = noDelay;
  181. }
  182. ~Phy()
  183. {
  184. while (!_socks.empty())
  185. this->close((PhySocket *)&(_socks.front()),true);
  186. ZT_PHY_CLOSE_SOCKET(_whackReceiveSocket);
  187. ZT_PHY_CLOSE_SOCKET(_whackSendSocket);
  188. }
  189. /**
  190. * Cause poll() to stop waiting immediately
  191. */
  192. inline void whack()
  193. {
  194. #if defined(_WIN32) || defined(_WIN64)
  195. ::send(_whackSendSocket,(const char *)this,1,0);
  196. #else
  197. ::write(_whackSendSocket,(PhySocket *)this,1);
  198. #endif
  199. }
  200. /**
  201. * @return Number of open sockets
  202. */
  203. inline unsigned long count() const throw() { return _socks.size(); }
  204. /**
  205. * @return Maximum number of sockets allowed
  206. */
  207. inline unsigned long maxCount() const throw() { return ZT_PHY_MAX_SOCKETS; }
  208. /**
  209. * Bind a UDP socket
  210. *
  211. * @param localAddress Local endpoint address and port
  212. * @param uptr Initial value of user pointer associated with this socket (default: NULL)
  213. * @param bufferSize Desired socket receive/send buffer size -- will set as close to this as possible (default: 0, leave alone)
  214. * @return Socket or NULL on failure to bind
  215. */
  216. inline PhySocket *udpBind(const struct sockaddr *localAddress,void *uptr = (void *)0,int bufferSize = 0)
  217. {
  218. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  219. return (PhySocket *)0;
  220. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_DGRAM,0);
  221. if (!ZT_PHY_SOCKFD_VALID(s))
  222. return (PhySocket *)0;
  223. if (bufferSize > 0) {
  224. int bs = bufferSize;
  225. while (bs >= 65536) {
  226. int tmpbs = bs;
  227. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  228. break;
  229. bs -= 16384;
  230. }
  231. bs = bufferSize;
  232. while (bs >= 65536) {
  233. int tmpbs = bs;
  234. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  235. break;
  236. bs -= 16384;
  237. }
  238. }
  239. #if defined(_WIN32) || defined(_WIN64)
  240. {
  241. BOOL f;
  242. if (localAddress->sa_family == AF_INET6) {
  243. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  244. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  245. }
  246. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  247. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  248. }
  249. #else // not Windows
  250. {
  251. int f;
  252. if (localAddress->sa_family == AF_INET6) {
  253. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  254. #ifdef IPV6_MTU_DISCOVER
  255. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  256. #endif
  257. }
  258. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  259. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  260. #ifdef IP_DONTFRAG
  261. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  262. #endif
  263. #ifdef IP_MTU_DISCOVER
  264. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  265. #endif
  266. }
  267. #endif // Windows or not
  268. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  269. ZT_PHY_CLOSE_SOCKET(s);
  270. return (PhySocket *)0;
  271. }
  272. #if defined(_WIN32) || defined(_WIN64)
  273. { u_long iMode=1; ioctlsocket(s,FIONBIO,&iMode); }
  274. #else
  275. fcntl(s,F_SETFL,O_NONBLOCK);
  276. #endif
  277. try {
  278. _socks.push_back(PhySocketImpl());
  279. } catch ( ... ) {
  280. ZT_PHY_CLOSE_SOCKET(s);
  281. return (PhySocket *)0;
  282. }
  283. PhySocketImpl &sws = _socks.back();
  284. if ((long)s > _nfds)
  285. _nfds = (long)s;
  286. FD_SET(s,&_readfds);
  287. sws.type = ZT_PHY_SOCKET_UDP;
  288. sws.sock = s;
  289. sws.uptr = uptr;
  290. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  291. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  292. return (PhySocket *)&sws;
  293. }
  294. /**
  295. * Send a UDP packet
  296. *
  297. * @param sock UDP socket
  298. * @param remoteAddress Destination address (must be correct type for socket)
  299. * @param data Data to send
  300. * @param len Length of packet
  301. * @return True if packet appears to have been sent successfully
  302. */
  303. inline bool udpSend(PhySocket *sock,const struct sockaddr *remoteAddress,const void *data,unsigned long len)
  304. {
  305. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  306. #if defined(_WIN32) || defined(_WIN64)
  307. return ((long)::sendto(sws.sock,reinterpret_cast<const char *>(data),len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  308. #else
  309. return ((long)::sendto(sws.sock,data,len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  310. #endif
  311. }
  312. /**
  313. * Bind a local listen socket to listen for new TCP connections
  314. *
  315. * @param localAddress Local address and port
  316. * @param uptr Initial value of uptr for new socket (default: NULL)
  317. * @return Socket or NULL on failure to bind
  318. */
  319. inline PhySocket *tcpListen(const struct sockaddr *localAddress,void *uptr = (void *)0)
  320. {
  321. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  322. return (PhySocket *)0;
  323. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_STREAM,0);
  324. if (!ZT_PHY_SOCKFD_VALID(s))
  325. return (PhySocket *)0;
  326. #if defined(_WIN32) || defined(_WIN64)
  327. {
  328. BOOL f;
  329. f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  330. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  331. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  332. u_long iMode=1;
  333. ioctlsocket(s,FIONBIO,&iMode);
  334. }
  335. #else
  336. {
  337. int f;
  338. f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  339. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  340. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  341. fcntl(s,F_SETFL,O_NONBLOCK);
  342. }
  343. #endif
  344. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  345. ZT_PHY_CLOSE_SOCKET(s);
  346. return (PhySocket *)0;
  347. }
  348. if (::listen(s,1024)) {
  349. ZT_PHY_CLOSE_SOCKET(s);
  350. return (PhySocket *)0;
  351. }
  352. try {
  353. _socks.push_back(PhySocketImpl());
  354. } catch ( ... ) {
  355. ZT_PHY_CLOSE_SOCKET(s);
  356. return (PhySocket *)0;
  357. }
  358. PhySocketImpl &sws = _socks.back();
  359. if ((long)s > _nfds)
  360. _nfds = (long)s;
  361. FD_SET(s,&_readfds);
  362. sws.type = ZT_PHY_SOCKET_TCP_LISTEN;
  363. sws.sock = s;
  364. sws.uptr = uptr;
  365. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  366. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  367. return (PhySocket *)&sws;
  368. }
  369. /**
  370. * Start a non-blocking connect; CONNECT handler is called on success or failure
  371. *
  372. * A return value of NULL indicates a synchronous failure such as a
  373. * failure to open a socket. The TCP connection handler is not called
  374. * in this case.
  375. *
  376. * It is possible on some platforms for an "instant connect" to occur,
  377. * such as when connecting to a loopback address. In this case, the
  378. * 'connected' result parameter will be set to 'true' and if the
  379. * 'callConnectHandler' flag is true (the default) the TCP connect
  380. * handler will be called before the function returns.
  381. *
  382. * These semantics can be a bit confusing, but they're less so than
  383. * the underlying semantics of asynchronous TCP connect.
  384. *
  385. * @param remoteAddress Remote address
  386. * @param connected Result parameter: set to whether an "instant connect" has occurred (true if yes)
  387. * @param uptr Initial value of uptr for new socket (default: NULL)
  388. * @param callConnectHandler If true, call TCP connect handler even if result is known before function exit (default: true)
  389. * @return New socket or NULL on failure
  390. */
  391. inline PhySocket *tcpConnect(const struct sockaddr *remoteAddress,bool &connected,void *uptr = (void *)0,bool callConnectHandler = true)
  392. {
  393. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  394. return (PhySocket *)0;
  395. ZT_PHY_SOCKFD_TYPE s = ::socket(remoteAddress->sa_family,SOCK_STREAM,0);
  396. if (!ZT_PHY_SOCKFD_VALID(s)) {
  397. connected = false;
  398. return (PhySocket *)0;
  399. }
  400. #if defined(_WIN32) || defined(_WIN64)
  401. {
  402. BOOL f;
  403. if (remoteAddress->sa_family == AF_INET6) { f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f)); }
  404. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  405. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  406. u_long iMode=1;
  407. ioctlsocket(s,FIONBIO,&iMode);
  408. }
  409. #else
  410. {
  411. int f;
  412. if (remoteAddress->sa_family == AF_INET6) { f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f)); }
  413. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  414. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  415. fcntl(s,F_SETFL,O_NONBLOCK);
  416. }
  417. #endif
  418. connected = true;
  419. if (::connect(s,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  420. connected = false;
  421. #if defined(_WIN32) || defined(_WIN64)
  422. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  423. #else
  424. if (errno != EINPROGRESS) {
  425. #endif
  426. ZT_PHY_CLOSE_SOCKET(s);
  427. return (PhySocket *)0;
  428. } // else connection is proceeding asynchronously...
  429. }
  430. try {
  431. _socks.push_back(PhySocketImpl());
  432. } catch ( ... ) {
  433. ZT_PHY_CLOSE_SOCKET(s);
  434. return (PhySocket *)0;
  435. }
  436. PhySocketImpl &sws = _socks.back();
  437. if ((long)s > _nfds)
  438. _nfds = (long)s;
  439. if (connected) {
  440. FD_SET(s,&_readfds);
  441. sws.type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  442. } else {
  443. FD_SET(s,&_writefds);
  444. #if defined(_WIN32) || defined(_WIN64)
  445. FD_SET(s,&_exceptfds);
  446. #endif
  447. sws.type = ZT_PHY_SOCKET_TCP_OUT_PENDING;
  448. }
  449. sws.sock = s;
  450. sws.uptr = uptr;
  451. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  452. memcpy(&(sws.saddr),remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  453. if ((callConnectHandler)&&(connected)) {
  454. try {
  455. _handler->phyOnTcpConnect((PhySocket *)&sws,&(sws.uptr),true);
  456. } catch ( ... ) {}
  457. }
  458. return (PhySocket *)&sws;
  459. }
  460. /**
  461. * Attempt to send data to a TCP connection (non-blocking)
  462. *
  463. * If -1 is returned, the socket should no longer be used as it is now
  464. * destroyed. If callCloseHandler is true, the close handler will be
  465. * called before the function returns.
  466. *
  467. * @param sock An open TCP socket (other socket types will fail)
  468. * @param data Data to send
  469. * @param len Length of data
  470. * @param callCloseHandler If true, call close handler on socket closing failure condition (default: true)
  471. * @return Number of bytes actually sent or -1 on fatal error (socket closure)
  472. */
  473. inline long tcpSend(PhySocket *sock,const void *data,unsigned long len,bool callCloseHandler = true)
  474. {
  475. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  476. #if defined(_WIN32) || defined(_WIN64)
  477. long n = (long)::send(sws.sock,reinterpret_cast<const char *>(data),len,0);
  478. if (n == SOCKET_ERROR) {
  479. switch(WSAGetLastError()) {
  480. case WSAEINTR:
  481. case WSAEWOULDBLOCK:
  482. return 0;
  483. default:
  484. this->close(sock,callCloseHandler);
  485. return -1;
  486. }
  487. }
  488. #else // not Windows
  489. long n = (long)::send(sws.sock,data,len,0);
  490. if (n < 0) {
  491. switch(errno) {
  492. #ifdef EAGAIN
  493. case EAGAIN:
  494. #endif
  495. #if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
  496. case EWOULDBLOCK:
  497. #endif
  498. #ifdef EINTR
  499. case EINTR:
  500. #endif
  501. return 0;
  502. default:
  503. this->close(sock,callCloseHandler);
  504. return -1;
  505. }
  506. }
  507. #endif // Windows or not
  508. return n;
  509. }
  510. /**
  511. * Set whether we want to be notified via the TCP writability handler when a socket is writable
  512. *
  513. * Call whack() if this is being done from another thread and you want
  514. * it to take effect immediately. Otherwise it is only guaranteed to
  515. * take effect on the next poll().
  516. *
  517. * @param sock TCP connection socket (other types are not valid)
  518. * @param notifyWritable Want writable notifications?
  519. */
  520. inline const void tcpSetNotifyWritable(PhySocket *sock,bool notifyWritable)
  521. {
  522. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  523. if (notifyWritable) {
  524. FD_SET(sws.sock,&_writefds);
  525. } else {
  526. FD_CLR(sws.sock,&_writefds);
  527. }
  528. }
  529. /**
  530. * Wait for activity and handle one or more events
  531. *
  532. * Note that this is not guaranteed to wait up to 'timeout' even
  533. * if nothing happens, as whack() or other events such as signals
  534. * may cause premature termination.
  535. *
  536. * @param timeout Timeout in milliseconds or 0 for none (forever)
  537. */
  538. inline void poll(unsigned long timeout)
  539. {
  540. char buf[131072];
  541. struct sockaddr_storage ss;
  542. struct timeval tv;
  543. fd_set rfds,wfds,efds;
  544. memcpy(&rfds,&_readfds,sizeof(rfds));
  545. memcpy(&wfds,&_writefds,sizeof(wfds));
  546. #if defined(_WIN32) || defined(_WIN64)
  547. memcpy(&efds,&_exceptfds,sizeof(efds));
  548. #else
  549. FD_ZERO(&efds);
  550. #endif
  551. tv.tv_sec = (long)(timeout / 1000);
  552. tv.tv_usec = (long)((timeout % 1000) * 1000);
  553. if (::select((int)_nfds + 1,&rfds,&wfds,&efds,(timeout > 0) ? &tv : (struct timeval *)0) <= 0)
  554. return;
  555. if (FD_ISSET(_whackReceiveSocket,&rfds)) {
  556. char tmp[16];
  557. #if defined(_WIN32) || defined(_WIN64)
  558. ::recv(_whackReceiveSocket,tmp,16,0);
  559. #else
  560. ::read(_whackReceiveSocket,tmp,16);
  561. #endif
  562. }
  563. bool atEnd = false;
  564. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin()),nexts;(!atEnd);s=nexts) {
  565. nexts = s; ++nexts; // we can delete the linked list item, so traverse now
  566. atEnd = (nexts == _socks.end()); // if we delete the last element, s!=_socks.end() will no longer terminate our loop
  567. switch (s->type) {
  568. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  569. #if defined(_WIN32) || defined(_WIN64)
  570. if (FD_ISSET(s->sock,&efds)) {
  571. this->close((PhySocket *)&(*s),true);
  572. } else // ... if
  573. #endif
  574. if (FD_ISSET(s->sock,&wfds)) {
  575. socklen_t slen = sizeof(ss);
  576. if (::getpeername(s->sock,(struct sockaddr *)&ss,&slen) != 0) {
  577. this->close((PhySocket *)&(*s),true);
  578. } else {
  579. s->type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  580. FD_SET(s->sock,&_readfds);
  581. FD_CLR(s->sock,&_writefds);
  582. #if defined(_WIN32) || defined(_WIN64)
  583. FD_CLR(s->sock,&_exceptfds);
  584. #endif
  585. try {
  586. _handler->phyOnTcpConnect((PhySocket *)&(*s),&(s->uptr),true);
  587. } catch ( ... ) {}
  588. }
  589. }
  590. break;
  591. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  592. case ZT_PHY_SOCKET_TCP_IN: {
  593. ZT_PHY_SOCKFD_TYPE sock = s->sock; // if closed, s->sock becomes invalid as s is no longer dereferencable
  594. if (FD_ISSET(sock,&rfds)) {
  595. long n = (long)::recv(sock,buf,sizeof(buf),0);
  596. if (n <= 0) {
  597. this->close((PhySocket *)&(*s),true);
  598. } else {
  599. try {
  600. _handler->phyOnTcpData((PhySocket *)&(*s),&(s->uptr),(void *)buf,(unsigned long)n);
  601. } catch ( ... ) {}
  602. }
  603. }
  604. if ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds))) {
  605. try {
  606. _handler->phyOnTcpWritable((PhySocket *)&(*s),&(s->uptr));
  607. } catch ( ... ) {}
  608. }
  609. } break;
  610. case ZT_PHY_SOCKET_TCP_LISTEN:
  611. if (FD_ISSET(s->sock,&rfds)) {
  612. memset(&ss,0,sizeof(ss));
  613. socklen_t slen = sizeof(ss);
  614. ZT_PHY_SOCKFD_TYPE newSock = ::accept(s->sock,(struct sockaddr *)&ss,&slen);
  615. if (ZT_PHY_SOCKFD_VALID(newSock)) {
  616. if (_socks.size() >= ZT_PHY_MAX_SOCKETS) {
  617. ZT_PHY_CLOSE_SOCKET(newSock);
  618. } else {
  619. #if defined(_WIN32) || defined(_WIN64)
  620. { BOOL f = (_noDelay ? TRUE : FALSE); setsockopt(newSock,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  621. { u_long iMode=1; ioctlsocket(newSock,FIONBIO,&iMode); }
  622. #else
  623. { int f = (_noDelay ? 1 : 0); setsockopt(newSock,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  624. fcntl(newSock,F_SETFL,O_NONBLOCK);
  625. #endif
  626. _socks.push_back(PhySocketImpl());
  627. PhySocketImpl &sws = _socks.back();
  628. FD_SET(newSock,&_readfds);
  629. if ((long)newSock > _nfds)
  630. _nfds = (long)newSock;
  631. sws.type = ZT_PHY_SOCKET_TCP_IN;
  632. sws.sock = newSock;
  633. sws.uptr = (void *)0;
  634. memcpy(&(sws.saddr),&ss,sizeof(struct sockaddr_storage));
  635. try {
  636. _handler->phyOnTcpAccept((PhySocket *)&(*s),(PhySocket *)&(_socks.back()),&(s->uptr),&(sws.uptr),(const struct sockaddr *)&(sws.saddr));
  637. } catch ( ... ) {}
  638. }
  639. }
  640. }
  641. break;
  642. case ZT_PHY_SOCKET_UDP:
  643. if (FD_ISSET(s->sock,&rfds)) {
  644. for(;;) {
  645. memset(&ss,0,sizeof(ss));
  646. socklen_t slen = sizeof(ss);
  647. long n = (long)::recvfrom(s->sock,buf,sizeof(buf),0,(struct sockaddr *)&ss,&slen);
  648. if (n > 0) {
  649. try {
  650. _handler->phyOnDatagram((PhySocket *)&(*s),&(s->uptr),(const struct sockaddr *)&ss,(void *)buf,(unsigned long)n);
  651. } catch ( ... ) {}
  652. } else if (n < 0)
  653. break;
  654. }
  655. }
  656. break;
  657. default:
  658. break;
  659. }
  660. }
  661. }
  662. /**
  663. * @param sock Socket to close
  664. * @param callHandlers If true, call handlers for TCP connect (success: false) or close (default: true)
  665. */
  666. inline void close(PhySocket *sock,bool callHandlers = true)
  667. {
  668. if (!sock)
  669. return;
  670. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  671. FD_CLR(sws.sock,&_readfds);
  672. FD_CLR(sws.sock,&_writefds);
  673. #if defined(_WIN32) || defined(_WIN64)
  674. FD_CLR(sws.sock,&_exceptfds);
  675. #endif
  676. ZT_PHY_CLOSE_SOCKET(sws.sock);
  677. switch(sws.type) {
  678. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  679. if (callHandlers) {
  680. try {
  681. _handler->phyOnTcpConnect(sock,&(sws.uptr),false);
  682. } catch ( ... ) {}
  683. }
  684. break;
  685. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  686. case ZT_PHY_SOCKET_TCP_IN:
  687. if (callHandlers) {
  688. try {
  689. _handler->phyOnTcpClose(sock,&(sws.uptr));
  690. } catch ( ... ) {}
  691. }
  692. break;
  693. default:
  694. break;
  695. }
  696. long oldSock = (long)sws.sock;
  697. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();++s) {
  698. if (reinterpret_cast<PhySocket *>(&(*s)) == sock) {
  699. _socks.erase(s);
  700. break;
  701. }
  702. }
  703. if (oldSock >= _nfds) {
  704. long nfds = (long)_whackSendSocket;
  705. if ((long)_whackReceiveSocket > nfds)
  706. nfds = (long)_whackReceiveSocket;
  707. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();++s) {
  708. if ((long)s->sock > nfds)
  709. nfds = (long)s->sock;
  710. }
  711. _nfds = nfds;
  712. }
  713. }
  714. };
  715. } // namespace ZeroTier
  716. #endif