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. #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_CLOSED = 0x00, // socket is closed, will be removed on next poll()
  113. ZT_PHY_SOCKET_TCP_OUT_PENDING = 0x01,
  114. ZT_PHY_SOCKET_TCP_OUT_CONNECTED = 0x02,
  115. ZT_PHY_SOCKET_TCP_IN = 0x03,
  116. ZT_PHY_SOCKET_TCP_LISTEN = 0x04,
  117. ZT_PHY_SOCKET_RAW = 0x05,
  118. ZT_PHY_SOCKET_UDP = 0x06
  119. };
  120. struct PhySocketImpl
  121. {
  122. PhySocketType type;
  123. ZT_PHY_SOCKFD_TYPE sock;
  124. void *uptr; // user-settable pointer
  125. ZT_PHY_SOCKADDR_STORAGE_TYPE saddr; // remote for TCP_OUT and TCP_IN, local for TCP_LISTEN, RAW, and UDP
  126. };
  127. std::list<PhySocketImpl> _socks;
  128. fd_set _readfds;
  129. fd_set _writefds;
  130. #if defined(_WIN32) || defined(_WIN64)
  131. fd_set _exceptfds;
  132. #endif
  133. long _nfds;
  134. ZT_PHY_SOCKFD_TYPE _whackReceiveSocket;
  135. ZT_PHY_SOCKFD_TYPE _whackSendSocket;
  136. bool _noDelay;
  137. public:
  138. /**
  139. * @param handler Pointer of type HANDLER_PTR_TYPE to handler
  140. * @param noDelay If true, disable TCP NAGLE algorithm on TCP sockets
  141. */
  142. Phy(HANDLER_PTR_TYPE handler,bool noDelay) :
  143. _handler(handler)
  144. {
  145. FD_ZERO(&_readfds);
  146. FD_ZERO(&_writefds);
  147. #if defined(_WIN32) || defined(_WIN64)
  148. FD_ZERO(&_exceptfds);
  149. SOCKET pipes[2];
  150. { // hack copied from StackOverflow, behaves a bit like pipe() on *nix systems
  151. struct sockaddr_in inaddr;
  152. struct sockaddr addr;
  153. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  154. if (lst == INVALID_SOCKET)
  155. throw std::runtime_error("unable to create pipes for select() abort");
  156. memset(&inaddr, 0, sizeof(inaddr));
  157. memset(&addr, 0, sizeof(addr));
  158. inaddr.sin_family = AF_INET;
  159. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  160. inaddr.sin_port = 0;
  161. int yes=1;
  162. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  163. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  164. listen(lst,1);
  165. int len=sizeof(inaddr);
  166. getsockname(lst, &addr,&len);
  167. pipes[0]=::socket(AF_INET, SOCK_STREAM,0);
  168. if (pipes[0] == INVALID_SOCKET)
  169. throw std::runtime_error("unable to create pipes for select() abort");
  170. connect(pipes[0],&addr,len);
  171. pipes[1]=accept(lst,0,0);
  172. closesocket(lst);
  173. }
  174. #else // not Windows
  175. int pipes[2];
  176. if (::pipe(pipes))
  177. throw std::runtime_error("unable to create pipes for select() abort");
  178. #endif // Windows or not
  179. _nfds = (pipes[0] > pipes[1]) ? (long)pipes[0] : (long)pipes[1];
  180. _whackReceiveSocket = pipes[0];
  181. _whackSendSocket = pipes[1];
  182. _noDelay = noDelay;
  183. }
  184. ~Phy()
  185. {
  186. for(typename std::list<PhySocketImpl>::const_iterator s(_socks.begin());s!=_socks.end();++s) {
  187. if (s->type != ZT_PHY_SOCKET_CLOSED)
  188. this->close((PhySocket *)&(*s),true);
  189. }
  190. ZT_PHY_CLOSE_SOCKET(_whackReceiveSocket);
  191. ZT_PHY_CLOSE_SOCKET(_whackSendSocket);
  192. }
  193. /**
  194. * Cause poll() to stop waiting immediately
  195. */
  196. inline void whack()
  197. {
  198. #if defined(_WIN32) || defined(_WIN64)
  199. ::send(_whackSendSocket,(const char *)this,1,0);
  200. #else
  201. ::write(_whackSendSocket,(PhySocket *)this,1);
  202. #endif
  203. }
  204. /**
  205. * @return Number of open sockets
  206. */
  207. inline unsigned long count() const throw() { return _socks.size(); }
  208. /**
  209. * @return Maximum number of sockets allowed
  210. */
  211. inline unsigned long maxCount() const throw() { return ZT_PHY_MAX_SOCKETS; }
  212. /**
  213. * Bind a UDP socket
  214. *
  215. * @param localAddress Local endpoint address and port
  216. * @param uptr Initial value of user pointer associated with this socket (default: NULL)
  217. * @param bufferSize Desired socket receive/send buffer size -- will set as close to this as possible (default: 0, leave alone)
  218. * @return Socket or NULL on failure to bind
  219. */
  220. inline PhySocket *udpBind(const struct sockaddr *localAddress,void *uptr = (void *)0,int bufferSize = 0)
  221. {
  222. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  223. return (PhySocket *)0;
  224. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_DGRAM,0);
  225. if (!ZT_PHY_SOCKFD_VALID(s))
  226. return (PhySocket *)0;
  227. if (bufferSize > 0) {
  228. int bs = bufferSize;
  229. while (bs >= 65536) {
  230. int tmpbs = bs;
  231. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  232. break;
  233. bs -= 16384;
  234. }
  235. bs = bufferSize;
  236. while (bs >= 65536) {
  237. int tmpbs = bs;
  238. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  239. break;
  240. bs -= 16384;
  241. }
  242. }
  243. #if defined(_WIN32) || defined(_WIN64)
  244. {
  245. BOOL f;
  246. if (localAddress->sa_family == AF_INET6) {
  247. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  248. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  249. }
  250. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  251. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  252. }
  253. #else // not Windows
  254. {
  255. int f;
  256. if (localAddress->sa_family == AF_INET6) {
  257. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  258. #ifdef IPV6_MTU_DISCOVER
  259. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  260. #endif
  261. }
  262. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  263. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  264. #ifdef IP_DONTFRAG
  265. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  266. #endif
  267. #ifdef IP_MTU_DISCOVER
  268. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  269. #endif
  270. }
  271. #endif // Windows or not
  272. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  273. ZT_PHY_CLOSE_SOCKET(s);
  274. return (PhySocket *)0;
  275. }
  276. #if defined(_WIN32) || defined(_WIN64)
  277. { u_long iMode=1; ioctlsocket(s,FIONBIO,&iMode); }
  278. #else
  279. fcntl(s,F_SETFL,O_NONBLOCK);
  280. #endif
  281. try {
  282. _socks.push_back(PhySocketImpl());
  283. } catch ( ... ) {
  284. ZT_PHY_CLOSE_SOCKET(s);
  285. return (PhySocket *)0;
  286. }
  287. PhySocketImpl &sws = _socks.back();
  288. if ((long)s > _nfds)
  289. _nfds = (long)s;
  290. FD_SET(s,&_readfds);
  291. sws.type = ZT_PHY_SOCKET_UDP;
  292. sws.sock = s;
  293. sws.uptr = uptr;
  294. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  295. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  296. return (PhySocket *)&sws;
  297. }
  298. /**
  299. * Send a UDP packet
  300. *
  301. * @param sock UDP socket
  302. * @param remoteAddress Destination address (must be correct type for socket)
  303. * @param data Data to send
  304. * @param len Length of packet
  305. * @return True if packet appears to have been sent successfully
  306. */
  307. inline bool udpSend(PhySocket *sock,const struct sockaddr *remoteAddress,const void *data,unsigned long len)
  308. {
  309. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  310. #if defined(_WIN32) || defined(_WIN64)
  311. 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);
  312. #else
  313. return ((long)::sendto(sws.sock,data,len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  314. #endif
  315. }
  316. /**
  317. * Bind a local listen socket to listen for new TCP connections
  318. *
  319. * @param localAddress Local address and port
  320. * @param uptr Initial value of uptr for new socket (default: NULL)
  321. * @return Socket or NULL on failure to bind
  322. */
  323. inline PhySocket *tcpListen(const struct sockaddr *localAddress,void *uptr = (void *)0)
  324. {
  325. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  326. return (PhySocket *)0;
  327. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_STREAM,0);
  328. if (!ZT_PHY_SOCKFD_VALID(s))
  329. return (PhySocket *)0;
  330. #if defined(_WIN32) || defined(_WIN64)
  331. {
  332. BOOL f;
  333. f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  334. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  335. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  336. u_long iMode=1;
  337. ioctlsocket(s,FIONBIO,&iMode);
  338. }
  339. #else
  340. {
  341. int f;
  342. f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  343. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  344. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  345. fcntl(s,F_SETFL,O_NONBLOCK);
  346. }
  347. #endif
  348. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  349. ZT_PHY_CLOSE_SOCKET(s);
  350. return (PhySocket *)0;
  351. }
  352. if (::listen(s,1024)) {
  353. ZT_PHY_CLOSE_SOCKET(s);
  354. return (PhySocket *)0;
  355. }
  356. try {
  357. _socks.push_back(PhySocketImpl());
  358. } catch ( ... ) {
  359. ZT_PHY_CLOSE_SOCKET(s);
  360. return (PhySocket *)0;
  361. }
  362. PhySocketImpl &sws = _socks.back();
  363. if ((long)s > _nfds)
  364. _nfds = (long)s;
  365. FD_SET(s,&_readfds);
  366. sws.type = ZT_PHY_SOCKET_TCP_LISTEN;
  367. sws.sock = s;
  368. sws.uptr = uptr;
  369. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  370. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  371. return (PhySocket *)&sws;
  372. }
  373. /**
  374. * Start a non-blocking connect; CONNECT handler is called on success or failure
  375. *
  376. * A return value of NULL indicates a synchronous failure such as a
  377. * failure to open a socket. The TCP connection handler is not called
  378. * in this case.
  379. *
  380. * It is possible on some platforms for an "instant connect" to occur,
  381. * such as when connecting to a loopback address. In this case, the
  382. * 'connected' result parameter will be set to 'true' and if the
  383. * 'callConnectHandler' flag is true (the default) the TCP connect
  384. * handler will be called before the function returns.
  385. *
  386. * These semantics can be a bit confusing, but they're less so than
  387. * the underlying semantics of asynchronous TCP connect.
  388. *
  389. * @param remoteAddress Remote address
  390. * @param connected Result parameter: set to whether an "instant connect" has occurred (true if yes)
  391. * @param uptr Initial value of uptr for new socket (default: NULL)
  392. * @param callConnectHandler If true, call TCP connect handler even if result is known before function exit (default: true)
  393. * @return New socket or NULL on failure
  394. */
  395. inline PhySocket *tcpConnect(const struct sockaddr *remoteAddress,bool &connected,void *uptr = (void *)0,bool callConnectHandler = true)
  396. {
  397. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  398. return (PhySocket *)0;
  399. ZT_PHY_SOCKFD_TYPE s = ::socket(remoteAddress->sa_family,SOCK_STREAM,0);
  400. if (!ZT_PHY_SOCKFD_VALID(s)) {
  401. connected = false;
  402. return (PhySocket *)0;
  403. }
  404. #if defined(_WIN32) || defined(_WIN64)
  405. {
  406. BOOL f;
  407. if (remoteAddress->sa_family == AF_INET6) { f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f)); }
  408. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  409. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  410. u_long iMode=1;
  411. ioctlsocket(s,FIONBIO,&iMode);
  412. }
  413. #else
  414. {
  415. int f;
  416. if (remoteAddress->sa_family == AF_INET6) { f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f)); }
  417. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  418. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  419. fcntl(s,F_SETFL,O_NONBLOCK);
  420. }
  421. #endif
  422. connected = true;
  423. if (::connect(s,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  424. connected = false;
  425. #if defined(_WIN32) || defined(_WIN64)
  426. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  427. #else
  428. if (errno != EINPROGRESS) {
  429. #endif
  430. ZT_PHY_CLOSE_SOCKET(s);
  431. return (PhySocket *)0;
  432. } // else connection is proceeding asynchronously...
  433. }
  434. try {
  435. _socks.push_back(PhySocketImpl());
  436. } catch ( ... ) {
  437. ZT_PHY_CLOSE_SOCKET(s);
  438. return (PhySocket *)0;
  439. }
  440. PhySocketImpl &sws = _socks.back();
  441. if ((long)s > _nfds)
  442. _nfds = (long)s;
  443. if (connected) {
  444. FD_SET(s,&_readfds);
  445. sws.type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  446. } else {
  447. FD_SET(s,&_writefds);
  448. #if defined(_WIN32) || defined(_WIN64)
  449. FD_SET(s,&_exceptfds);
  450. #endif
  451. sws.type = ZT_PHY_SOCKET_TCP_OUT_PENDING;
  452. }
  453. sws.sock = s;
  454. sws.uptr = uptr;
  455. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  456. memcpy(&(sws.saddr),remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  457. if ((callConnectHandler)&&(connected)) {
  458. try {
  459. _handler->phyOnTcpConnect((PhySocket *)&sws,&(sws.uptr),true);
  460. } catch ( ... ) {}
  461. }
  462. return (PhySocket *)&sws;
  463. }
  464. /**
  465. * Attempt to send data to a TCP connection (non-blocking)
  466. *
  467. * If -1 is returned, the socket should no longer be used as it is now
  468. * destroyed. If callCloseHandler is true, the close handler will be
  469. * called before the function returns.
  470. *
  471. * @param sock An open TCP socket (other socket types will fail)
  472. * @param data Data to send
  473. * @param len Length of data
  474. * @param callCloseHandler If true, call close handler on socket closing failure condition (default: true)
  475. * @return Number of bytes actually sent or -1 on fatal error (socket closure)
  476. */
  477. inline long tcpSend(PhySocket *sock,const void *data,unsigned long len,bool callCloseHandler = true)
  478. {
  479. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  480. #if defined(_WIN32) || defined(_WIN64)
  481. long n = (long)::send(sws.sock,reinterpret_cast<const char *>(data),len,0);
  482. if (n == SOCKET_ERROR) {
  483. switch(WSAGetLastError()) {
  484. case WSAEINTR:
  485. case WSAEWOULDBLOCK:
  486. return 0;
  487. default:
  488. this->close(sock,callCloseHandler);
  489. return -1;
  490. }
  491. }
  492. #else // not Windows
  493. long n = (long)::send(sws.sock,data,len,0);
  494. if (n < 0) {
  495. switch(errno) {
  496. #ifdef EAGAIN
  497. case EAGAIN:
  498. #endif
  499. #if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
  500. case EWOULDBLOCK:
  501. #endif
  502. #ifdef EINTR
  503. case EINTR:
  504. #endif
  505. return 0;
  506. default:
  507. this->close(sock,callCloseHandler);
  508. return -1;
  509. }
  510. }
  511. #endif // Windows or not
  512. return n;
  513. }
  514. /**
  515. * Set whether we want to be notified via the TCP writability handler when a socket is writable
  516. *
  517. * Call whack() if this is being done from another thread and you want
  518. * it to take effect immediately. Otherwise it is only guaranteed to
  519. * take effect on the next poll().
  520. *
  521. * @param sock TCP connection socket (other types are not valid)
  522. * @param notifyWritable Want writable notifications?
  523. */
  524. inline const void tcpSetNotifyWritable(PhySocket *sock,bool notifyWritable)
  525. {
  526. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  527. if (notifyWritable) {
  528. FD_SET(sws.sock,&_writefds);
  529. } else {
  530. FD_CLR(sws.sock,&_writefds);
  531. }
  532. }
  533. /**
  534. * Wait for activity and handle one or more events
  535. *
  536. * Note that this is not guaranteed to wait up to 'timeout' even
  537. * if nothing happens, as whack() or other events such as signals
  538. * may cause premature termination.
  539. *
  540. * @param timeout Timeout in milliseconds or 0 for none (forever)
  541. */
  542. inline void poll(unsigned long timeout)
  543. {
  544. char buf[131072];
  545. struct sockaddr_storage ss;
  546. struct timeval tv;
  547. fd_set rfds,wfds,efds;
  548. memcpy(&rfds,&_readfds,sizeof(rfds));
  549. memcpy(&wfds,&_writefds,sizeof(wfds));
  550. #if defined(_WIN32) || defined(_WIN64)
  551. memcpy(&efds,&_exceptfds,sizeof(efds));
  552. #else
  553. FD_ZERO(&efds);
  554. #endif
  555. tv.tv_sec = (long)(timeout / 1000);
  556. tv.tv_usec = (long)((timeout % 1000) * 1000);
  557. if (::select((int)_nfds + 1,&rfds,&wfds,&efds,(timeout > 0) ? &tv : (struct timeval *)0) <= 0)
  558. return;
  559. if (FD_ISSET(_whackReceiveSocket,&rfds)) {
  560. char tmp[16];
  561. #if defined(_WIN32) || defined(_WIN64)
  562. ::recv(_whackReceiveSocket,tmp,16,0);
  563. #else
  564. ::read(_whackReceiveSocket,tmp,16);
  565. #endif
  566. }
  567. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();) {
  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. if (s->type == ZT_PHY_SOCKET_CLOSED)
  662. _socks.erase(s++);
  663. else ++s;
  664. }
  665. }
  666. /**
  667. * @param sock Socket to close
  668. * @param callHandlers If true, call handlers for TCP connect (success: false) or close (default: true)
  669. */
  670. inline void close(PhySocket *sock,bool callHandlers = true)
  671. {
  672. if (!sock)
  673. return;
  674. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  675. if (sws.type == ZT_PHY_SOCKET_CLOSED)
  676. return;
  677. FD_CLR(sws.sock,&_readfds);
  678. FD_CLR(sws.sock,&_writefds);
  679. #if defined(_WIN32) || defined(_WIN64)
  680. FD_CLR(sws.sock,&_exceptfds);
  681. #endif
  682. ZT_PHY_CLOSE_SOCKET(sws.sock);
  683. switch(sws.type) {
  684. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  685. if (callHandlers) {
  686. try {
  687. _handler->phyOnTcpConnect(sock,&(sws.uptr),false);
  688. } catch ( ... ) {}
  689. }
  690. break;
  691. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  692. case ZT_PHY_SOCKET_TCP_IN:
  693. if (callHandlers) {
  694. try {
  695. _handler->phyOnTcpClose(sock,&(sws.uptr));
  696. } catch ( ... ) {}
  697. }
  698. break;
  699. default:
  700. break;
  701. }
  702. // Causes entry to be deleted from list in poll(), ignored elsewhere
  703. sws.type = ZT_PHY_SOCKET_CLOSED;
  704. if (sws.sock >= _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 ((s->type != ZT_PHY_SOCKET_CLOSED)&&((long)s->sock > nfds))
  710. nfds = (long)s->sock;
  711. }
  712. _nfds = nfds;
  713. }
  714. }
  715. };
  716. } // namespace ZeroTier
  717. #endif