Phy.hpp 24 KB

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