Phy.hpp 25 KB

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