Phy.hpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #ifndef ZT_PHY_HPP
  19. #define ZT_PHY_HPP
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <list>
  24. #include <stdexcept>
  25. #if defined(_WIN32) || defined(_WIN64)
  26. #include <WinSock2.h>
  27. #include <WS2tcpip.h>
  28. #include <Windows.h>
  29. #define ZT_PHY_SOCKFD_TYPE SOCKET
  30. #define ZT_PHY_SOCKFD_NULL (INVALID_SOCKET)
  31. #define ZT_PHY_SOCKFD_VALID(s) ((s) != INVALID_SOCKET)
  32. #define ZT_PHY_CLOSE_SOCKET(s) ::closesocket(s)
  33. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  34. #define ZT_PHY_MAX_INTERCEPTS ZT_PHY_MAX_SOCKETS
  35. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  36. #else // not Windows
  37. #include <errno.h>
  38. #include <signal.h>
  39. #include <unistd.h>
  40. #include <fcntl.h>
  41. #include <sys/time.h>
  42. #include <sys/types.h>
  43. #include <sys/select.h>
  44. #include <sys/socket.h>
  45. #include <sys/un.h>
  46. #include <arpa/inet.h>
  47. #include <netinet/in.h>
  48. #include <netinet/tcp.h>
  49. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  50. #ifndef IPV6_DONTFRAG
  51. #define IPV6_DONTFRAG 62
  52. #endif
  53. #endif
  54. #define ZT_PHY_SOCKFD_TYPE int
  55. #define ZT_PHY_SOCKFD_NULL (-1)
  56. #define ZT_PHY_SOCKFD_VALID(s) ((s) > -1)
  57. #define ZT_PHY_CLOSE_SOCKET(s) ::close(s)
  58. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  59. #define ZT_PHY_MAX_INTERCEPTS ZT_PHY_MAX_SOCKETS
  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. * For all platforms:
  77. *
  78. * phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  79. * phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  80. * phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  81. * phyOnTcpClose(PhySocket *sock,void **uptr)
  82. * phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  83. * phyOnTcpWritable(PhySocket *sock,void **uptr)
  84. * phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  85. *
  86. * On Linux/OSX/Unix only (not required/used on Windows or elsewhere):
  87. *
  88. * phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  89. * phyOnUnixClose(PhySocket *sock,void **uptr)
  90. * phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  91. * phyOnUnixWritable(PhySocket *sock,void **uptr)
  92. *
  93. * These templates typically refer to function objects. Templates are used to
  94. * avoid the call overhead of indirection, which is surprisingly high for high
  95. * bandwidth applications pushing a lot of packets.
  96. *
  97. * The 'sock' pointer above is an opaque pointer to a socket. Each socket
  98. * has a 'uptr' user-settable/modifiable pointer associated with it, which
  99. * can be set on bind/connect calls and is passed as a void ** to permit
  100. * resetting at any time. The ACCEPT handler takes two sets of sock and
  101. * uptr: sockL and uptrL for the listen socket, and sockN and uptrN for
  102. * the new TCP connection socket that has just been created.
  103. *
  104. * Handlers are always called. On outgoing TCP connection, CONNECT is always
  105. * called on either success or failure followed by DATA and/or WRITABLE as
  106. * indicated. On socket close, handlers are called unless close() is told
  107. * explicitly not to call handlers. It is safe to close a socket within a
  108. * handler, and in that case close() can be told not to call handlers to
  109. * prevent recursion.
  110. *
  111. * This isn't thread-safe with the exception of whack(), which is safe to
  112. * call from another thread to abort poll().
  113. */
  114. template <typename HANDLER_PTR_TYPE>
  115. class Phy
  116. {
  117. private:
  118. HANDLER_PTR_TYPE _handler;
  119. enum PhySocketType
  120. {
  121. ZT_PHY_SOCKET_CLOSED = 0x00, // socket is closed, will be removed on next poll()
  122. ZT_PHY_SOCKET_TCP_OUT_PENDING = 0x01,
  123. ZT_PHY_SOCKET_TCP_OUT_CONNECTED = 0x02,
  124. ZT_PHY_SOCKET_TCP_IN = 0x03,
  125. ZT_PHY_SOCKET_TCP_LISTEN = 0x04,
  126. ZT_PHY_SOCKET_UDP = 0x05,
  127. ZT_PHY_SOCKET_FD = 0x06,
  128. ZT_PHY_SOCKET_UNIX_IN = 0x07,
  129. ZT_PHY_SOCKET_UNIX_LISTEN = 0x08
  130. };
  131. struct PhySocketImpl
  132. {
  133. PhySocketType type;
  134. ZT_PHY_SOCKFD_TYPE sock;
  135. void *uptr; // user-settable pointer
  136. ZT_PHY_SOCKADDR_STORAGE_TYPE saddr; // remote for TCP_OUT and TCP_IN, local for TCP_LISTEN, RAW, and UDP
  137. };
  138. std::list<PhySocketImpl> _socks;
  139. fd_set _readfds;
  140. fd_set _writefds;
  141. #if defined(_WIN32) || defined(_WIN64)
  142. fd_set _exceptfds;
  143. #endif
  144. long _nfds;
  145. ZT_PHY_SOCKFD_TYPE _whackReceiveSocket;
  146. ZT_PHY_SOCKFD_TYPE _whackSendSocket;
  147. bool _noDelay;
  148. bool _noCheck;
  149. public:
  150. /**
  151. * @param handler Pointer of type HANDLER_PTR_TYPE to handler
  152. * @param noDelay If true, disable TCP NAGLE algorithm on TCP sockets
  153. * @param noCheck If true, attempt to set UDP SO_NO_CHECK option to disable sending checksums
  154. */
  155. Phy(HANDLER_PTR_TYPE handler,bool noDelay,bool noCheck) :
  156. _handler(handler)
  157. {
  158. FD_ZERO(&_readfds);
  159. FD_ZERO(&_writefds);
  160. #if defined(_WIN32) || defined(_WIN64)
  161. FD_ZERO(&_exceptfds);
  162. SOCKET pipes[2];
  163. { // hack copied from StackOverflow, behaves a bit like pipe() on *nix systems
  164. struct sockaddr_in inaddr;
  165. struct sockaddr addr;
  166. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  167. if (lst == INVALID_SOCKET)
  168. throw std::runtime_error("unable to create pipes for select() abort");
  169. memset(&inaddr, 0, sizeof(inaddr));
  170. memset(&addr, 0, sizeof(addr));
  171. inaddr.sin_family = AF_INET;
  172. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  173. inaddr.sin_port = 0;
  174. int yes=1;
  175. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  176. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  177. listen(lst,1);
  178. int len=sizeof(inaddr);
  179. getsockname(lst, &addr,&len);
  180. pipes[0]=::socket(AF_INET, SOCK_STREAM,0);
  181. if (pipes[0] == INVALID_SOCKET)
  182. throw std::runtime_error("unable to create pipes for select() abort");
  183. connect(pipes[0],&addr,len);
  184. pipes[1]=accept(lst,0,0);
  185. closesocket(lst);
  186. }
  187. #else // not Windows
  188. int pipes[2];
  189. if (::pipe(pipes))
  190. throw std::runtime_error("unable to create pipes for select() abort");
  191. #endif // Windows or not
  192. _nfds = (pipes[0] > pipes[1]) ? (long)pipes[0] : (long)pipes[1];
  193. _whackReceiveSocket = pipes[0];
  194. _whackSendSocket = pipes[1];
  195. _noDelay = noDelay;
  196. _noCheck = noCheck;
  197. }
  198. ~Phy()
  199. {
  200. for(typename std::list<PhySocketImpl>::const_iterator s(_socks.begin());s!=_socks.end();++s) {
  201. if (s->type != ZT_PHY_SOCKET_CLOSED)
  202. this->close((PhySocket *)&(*s),true);
  203. }
  204. ZT_PHY_CLOSE_SOCKET(_whackReceiveSocket);
  205. ZT_PHY_CLOSE_SOCKET(_whackSendSocket);
  206. }
  207. /**
  208. * @param s Socket object
  209. * @return Underlying OS-type (usually int or long) file descriptor associated with object
  210. */
  211. static inline ZT_PHY_SOCKFD_TYPE getDescriptor(PhySocket *s) throw() { return reinterpret_cast<PhySocketImpl *>(s)->sock; }
  212. /**
  213. * @param s Socket object
  214. * @return Pointer to user object
  215. */
  216. static inline void** getuptr(PhySocket *s) throw() { return &(reinterpret_cast<PhySocketImpl *>(s)->uptr); }
  217. /**
  218. * Cause poll() to stop waiting immediately
  219. *
  220. * This can be used to reset the polling loop after changes that require
  221. * attention, or to shut down a background thread that is waiting, etc.
  222. */
  223. inline void whack()
  224. {
  225. #if defined(_WIN32) || defined(_WIN64)
  226. ::send(_whackSendSocket,(const char *)this,1,0);
  227. #else
  228. ::write(_whackSendSocket,(PhySocket *)this,1);
  229. #endif
  230. }
  231. /**
  232. * @return Number of open sockets
  233. */
  234. inline unsigned long count() const throw() { return _socks.size(); }
  235. /**
  236. * @return Maximum number of sockets allowed
  237. */
  238. inline unsigned long maxCount() const throw() { return ZT_PHY_MAX_SOCKETS; }
  239. /**
  240. * Wrap a raw file descriptor in a PhySocket structure
  241. *
  242. * This can be used to select/poll on a raw file descriptor as part of this
  243. * class's I/O loop. By default the fd is set for read notification but
  244. * this can be controlled with setNotifyReadable(). When any detected
  245. * condition is present, the phyOnFileDescriptorActivity() callback is
  246. * called with one or both of its arguments 'true'.
  247. *
  248. * The Phy<>::close() method *must* be called when you're done with this
  249. * file descriptor to remove it from the select/poll set, but unlike other
  250. * types of sockets Phy<> does not actually close the underlying fd or
  251. * otherwise manage its life cycle. There is also no close notification
  252. * callback for this fd, since Phy<> doesn't actually perform reading or
  253. * writing or detect error conditions. This is only useful for adding a
  254. * file descriptor to Phy<> to select/poll on it.
  255. *
  256. * @param fd Raw file descriptor
  257. * @param uptr User pointer to supply to callbacks
  258. * @return PhySocket wrapping fd or NULL on failure (out of memory or too many sockets)
  259. */
  260. inline PhySocket *wrapSocket(ZT_PHY_SOCKFD_TYPE fd,void *uptr = (void *)0)
  261. {
  262. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  263. return (PhySocket *)0;
  264. try {
  265. _socks.push_back(PhySocketImpl());
  266. } catch ( ... ) {
  267. return (PhySocket *)0;
  268. }
  269. PhySocketImpl &sws = _socks.back();
  270. if ((long)fd > _nfds)
  271. _nfds = (long)fd;
  272. FD_SET(fd,&_readfds);
  273. sws.type = ZT_PHY_SOCKET_UNIX_IN; /* TODO: Type was changed to allow for CBs with new RPC model */
  274. sws.sock = fd;
  275. sws.uptr = uptr;
  276. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  277. // no sockaddr for this socket type, leave saddr null
  278. return (PhySocket *)&sws;
  279. }
  280. /**
  281. * Bind a UDP socket
  282. *
  283. * @param localAddress Local endpoint address and port
  284. * @param uptr Initial value of user pointer associated with this socket (default: NULL)
  285. * @param bufferSize Desired socket receive/send buffer size -- will set as close to this as possible (default: 0, leave alone)
  286. * @return Socket or NULL on failure to bind
  287. */
  288. inline PhySocket *udpBind(const struct sockaddr *localAddress,void *uptr = (void *)0,int bufferSize = 0)
  289. {
  290. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  291. return (PhySocket *)0;
  292. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_DGRAM,0);
  293. if (!ZT_PHY_SOCKFD_VALID(s))
  294. return (PhySocket *)0;
  295. if (bufferSize > 0) {
  296. int bs = bufferSize;
  297. while (bs >= 65536) {
  298. int tmpbs = bs;
  299. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  300. break;
  301. bs -= 16384;
  302. }
  303. bs = bufferSize;
  304. while (bs >= 65536) {
  305. int tmpbs = bs;
  306. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  307. break;
  308. bs -= 16384;
  309. }
  310. }
  311. #if defined(_WIN32) || defined(_WIN64)
  312. {
  313. BOOL f;
  314. if (localAddress->sa_family == AF_INET6) {
  315. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  316. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  317. }
  318. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  319. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  320. }
  321. #else // not Windows
  322. {
  323. int f;
  324. if (localAddress->sa_family == AF_INET6) {
  325. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  326. #ifdef IPV6_MTU_DISCOVER
  327. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  328. #endif
  329. #ifdef IPV6_DONTFRAG
  330. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  331. #endif
  332. }
  333. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  334. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  335. #ifdef IP_DONTFRAG
  336. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  337. #endif
  338. #ifdef IP_MTU_DISCOVER
  339. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  340. #endif
  341. #ifdef SO_NO_CHECK
  342. // For now at least we only set SO_NO_CHECK on IPv4 sockets since some
  343. // IPv6 stacks incorrectly discard zero checksum packets. May remove
  344. // this restriction later once broken stuff dies more.
  345. if ((localAddress->sa_family == AF_INET)&&(_noCheck)) {
  346. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  347. }
  348. #endif
  349. }
  350. #endif // Windows or not
  351. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  352. ZT_PHY_CLOSE_SOCKET(s);
  353. return (PhySocket *)0;
  354. }
  355. #if defined(_WIN32) || defined(_WIN64)
  356. { u_long iMode=1; ioctlsocket(s,FIONBIO,&iMode); }
  357. #else
  358. fcntl(s,F_SETFL,O_NONBLOCK);
  359. #endif
  360. try {
  361. _socks.push_back(PhySocketImpl());
  362. } catch ( ... ) {
  363. ZT_PHY_CLOSE_SOCKET(s);
  364. return (PhySocket *)0;
  365. }
  366. PhySocketImpl &sws = _socks.back();
  367. if ((long)s > _nfds)
  368. _nfds = (long)s;
  369. FD_SET(s,&_readfds);
  370. sws.type = ZT_PHY_SOCKET_UDP;
  371. sws.sock = s;
  372. sws.uptr = uptr;
  373. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  374. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  375. return (PhySocket *)&sws;
  376. }
  377. /**
  378. * Set the IP TTL for the next outgoing packet (for IPv4 UDP sockets only)
  379. *
  380. * @param ttl New TTL (0 or >255 will set it to 255)
  381. * @return True on success
  382. */
  383. inline bool setIp4UdpTtl(PhySocket *sock,unsigned int ttl)
  384. {
  385. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  386. #if defined(_WIN32) || defined(_WIN64)
  387. DWORD tmp = ((ttl == 0)||(ttl > 255)) ? 255 : (DWORD)ttl;
  388. return (::setsockopt(sws.sock,IPPROTO_IP,IP_TTL,(const char *)&tmp,sizeof(tmp)) == 0);
  389. #else
  390. int tmp = ((ttl == 0)||(ttl > 255)) ? 255 : (int)ttl;
  391. return (::setsockopt(sws.sock,IPPROTO_IP,IP_TTL,(void *)&tmp,sizeof(tmp)) == 0);
  392. #endif
  393. }
  394. /**
  395. * Send a UDP packet
  396. *
  397. * @param sock UDP socket
  398. * @param remoteAddress Destination address (must be correct type for socket)
  399. * @param data Data to send
  400. * @param len Length of packet
  401. * @return True if packet appears to have been sent successfully
  402. */
  403. inline bool udpSend(PhySocket *sock,const struct sockaddr *remoteAddress,const void *data,unsigned long len)
  404. {
  405. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  406. #if defined(_WIN32) || defined(_WIN64)
  407. 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);
  408. #else
  409. return ((long)::sendto(sws.sock,data,len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  410. #endif
  411. }
  412. #ifdef __UNIX_LIKE__
  413. /**
  414. * Listen for connections on a Unix domain socket
  415. *
  416. * @param path Path to Unix domain socket
  417. * @param uptr Arbitrary pointer to associate
  418. * @return PhySocket or NULL if cannot bind
  419. */
  420. inline PhySocket *unixListen(const char *path,void *uptr = (void *)0)
  421. {
  422. struct sockaddr_un sun;
  423. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  424. return (PhySocket *)0;
  425. memset(&sun,0,sizeof(sun));
  426. sun.sun_family = AF_UNIX;
  427. if (strlen(path) >= sizeof(sun.sun_path))
  428. return (PhySocket *)0;
  429. strcpy(sun.sun_path,path);
  430. ZT_PHY_SOCKFD_TYPE s = ::socket(PF_UNIX,SOCK_STREAM,0);
  431. if (!ZT_PHY_SOCKFD_VALID(s))
  432. return (PhySocket *)0;
  433. ::fcntl(s,F_SETFL,O_NONBLOCK);
  434. ::unlink(path);
  435. if (::bind(s,(struct sockaddr *)&sun,sizeof(struct sockaddr_un)) != 0) {
  436. ZT_PHY_CLOSE_SOCKET(s);
  437. return (PhySocket *)0;
  438. }
  439. if (::listen(s,128) != 0) {
  440. ZT_PHY_CLOSE_SOCKET(s);
  441. return (PhySocket *)0;
  442. }
  443. try {
  444. _socks.push_back(PhySocketImpl());
  445. } catch ( ... ) {
  446. ZT_PHY_CLOSE_SOCKET(s);
  447. return (PhySocket *)0;
  448. }
  449. PhySocketImpl &sws = _socks.back();
  450. if ((long)s > _nfds)
  451. _nfds = (long)s;
  452. FD_SET(s,&_readfds);
  453. sws.type = ZT_PHY_SOCKET_UNIX_LISTEN;
  454. sws.sock = s;
  455. sws.uptr = uptr;
  456. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  457. memcpy(&(sws.saddr),&sun,sizeof(struct sockaddr_un));
  458. return (PhySocket *)&sws;
  459. }
  460. #endif // __UNIX_LIKE__
  461. /**
  462. * Bind a local listen socket to listen for new TCP connections
  463. *
  464. * @param localAddress Local address and port
  465. * @param uptr Initial value of uptr for new socket (default: NULL)
  466. * @return Socket or NULL on failure to bind
  467. */
  468. inline PhySocket *tcpListen(const struct sockaddr *localAddress,void *uptr = (void *)0)
  469. {
  470. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  471. return (PhySocket *)0;
  472. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_STREAM,0);
  473. if (!ZT_PHY_SOCKFD_VALID(s))
  474. return (PhySocket *)0;
  475. #if defined(_WIN32) || defined(_WIN64)
  476. {
  477. BOOL f;
  478. f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  479. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  480. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  481. u_long iMode=1;
  482. ioctlsocket(s,FIONBIO,&iMode);
  483. }
  484. #else
  485. {
  486. int f;
  487. f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  488. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  489. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  490. fcntl(s,F_SETFL,O_NONBLOCK);
  491. }
  492. #endif
  493. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  494. ZT_PHY_CLOSE_SOCKET(s);
  495. return (PhySocket *)0;
  496. }
  497. if (::listen(s,1024)) {
  498. ZT_PHY_CLOSE_SOCKET(s);
  499. return (PhySocket *)0;
  500. }
  501. try {
  502. _socks.push_back(PhySocketImpl());
  503. } catch ( ... ) {
  504. ZT_PHY_CLOSE_SOCKET(s);
  505. return (PhySocket *)0;
  506. }
  507. PhySocketImpl &sws = _socks.back();
  508. if ((long)s > _nfds)
  509. _nfds = (long)s;
  510. FD_SET(s,&_readfds);
  511. sws.type = ZT_PHY_SOCKET_TCP_LISTEN;
  512. sws.sock = s;
  513. sws.uptr = uptr;
  514. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  515. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  516. return (PhySocket *)&sws;
  517. }
  518. /**
  519. * Start a non-blocking connect; CONNECT handler is called on success or failure
  520. *
  521. * A return value of NULL indicates a synchronous failure such as a
  522. * failure to open a socket. The TCP connection handler is not called
  523. * in this case.
  524. *
  525. * It is possible on some platforms for an "instant connect" to occur,
  526. * such as when connecting to a loopback address. In this case, the
  527. * 'connected' result parameter will be set to 'true' and if the
  528. * 'callConnectHandler' flag is true (the default) the TCP connect
  529. * handler will be called before the function returns.
  530. *
  531. * These semantics can be a bit confusing, but they're less so than
  532. * the underlying semantics of asynchronous TCP connect.
  533. *
  534. * @param remoteAddress Remote address
  535. * @param connected Result parameter: set to whether an "instant connect" has occurred (true if yes)
  536. * @param uptr Initial value of uptr for new socket (default: NULL)
  537. * @param callConnectHandler If true, call TCP connect handler even if result is known before function exit (default: true)
  538. * @return New socket or NULL on failure
  539. */
  540. inline PhySocket *tcpConnect(const struct sockaddr *remoteAddress,bool &connected,void *uptr = (void *)0,bool callConnectHandler = true)
  541. {
  542. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  543. return (PhySocket *)0;
  544. ZT_PHY_SOCKFD_TYPE s = ::socket(remoteAddress->sa_family,SOCK_STREAM,0);
  545. if (!ZT_PHY_SOCKFD_VALID(s)) {
  546. connected = false;
  547. return (PhySocket *)0;
  548. }
  549. #if defined(_WIN32) || defined(_WIN64)
  550. {
  551. BOOL f;
  552. if (remoteAddress->sa_family == AF_INET6) { f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f)); }
  553. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  554. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  555. u_long iMode=1;
  556. ioctlsocket(s,FIONBIO,&iMode);
  557. }
  558. #else
  559. {
  560. int f;
  561. if (remoteAddress->sa_family == AF_INET6) { f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f)); }
  562. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  563. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  564. fcntl(s,F_SETFL,O_NONBLOCK);
  565. }
  566. #endif
  567. connected = true;
  568. if (::connect(s,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  569. connected = false;
  570. #if defined(_WIN32) || defined(_WIN64)
  571. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  572. #else
  573. if (errno != EINPROGRESS) {
  574. #endif
  575. ZT_PHY_CLOSE_SOCKET(s);
  576. return (PhySocket *)0;
  577. } // else connection is proceeding asynchronously...
  578. }
  579. try {
  580. _socks.push_back(PhySocketImpl());
  581. } catch ( ... ) {
  582. ZT_PHY_CLOSE_SOCKET(s);
  583. return (PhySocket *)0;
  584. }
  585. PhySocketImpl &sws = _socks.back();
  586. if ((long)s > _nfds)
  587. _nfds = (long)s;
  588. if (connected) {
  589. FD_SET(s,&_readfds);
  590. sws.type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  591. } else {
  592. FD_SET(s,&_writefds);
  593. #if defined(_WIN32) || defined(_WIN64)
  594. FD_SET(s,&_exceptfds);
  595. #endif
  596. sws.type = ZT_PHY_SOCKET_TCP_OUT_PENDING;
  597. }
  598. sws.sock = s;
  599. sws.uptr = uptr;
  600. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  601. memcpy(&(sws.saddr),remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  602. if ((callConnectHandler)&&(connected)) {
  603. try {
  604. _handler->phyOnTcpConnect((PhySocket *)&sws,&(sws.uptr),true);
  605. } catch ( ... ) {}
  606. }
  607. return (PhySocket *)&sws;
  608. }
  609. /**
  610. * Try to set buffer sizes as close to the given value as possible
  611. *
  612. * This will try the specified value and then lower values in 16K increments
  613. * until one works.
  614. *
  615. * @param sock Socket
  616. * @param bufferSize Desired buffer sizes
  617. */
  618. inline void setBufferSizes(const PhySocket *sock,int bufferSize)
  619. {
  620. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  621. if (bufferSize > 0) {
  622. int bs = bufferSize;
  623. while (bs >= 65536) {
  624. int tmpbs = bs;
  625. if (::setsockopt(sws.sock,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  626. break;
  627. bs -= 16384;
  628. }
  629. bs = bufferSize;
  630. while (bs >= 65536) {
  631. int tmpbs = bs;
  632. if (::setsockopt(sws.sock,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  633. break;
  634. bs -= 16384;
  635. }
  636. }
  637. }
  638. /**
  639. * Attempt to send data to a stream socket (non-blocking)
  640. *
  641. * If -1 is returned, the socket should no longer be used as it is now
  642. * destroyed. If callCloseHandler is true, the close handler will be
  643. * called before the function returns.
  644. *
  645. * This can be used with TCP, Unix, or socket pair sockets.
  646. *
  647. * @param sock An open stream socket (other socket types will fail)
  648. * @param data Data to send
  649. * @param len Length of data
  650. * @param callCloseHandler If true, call close handler on socket closing failure condition (default: true)
  651. * @return Number of bytes actually sent or -1 on fatal error (socket closure)
  652. */
  653. inline long streamSend(PhySocket *sock,const void *data,unsigned long len,bool callCloseHandler = true)
  654. {
  655. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  656. #if defined(_WIN32) || defined(_WIN64)
  657. long n = (long)::send(sws.sock,reinterpret_cast<const char *>(data),len,0);
  658. if (n == SOCKET_ERROR) {
  659. switch(WSAGetLastError()) {
  660. case WSAEINTR:
  661. case WSAEWOULDBLOCK:
  662. return 0;
  663. default:
  664. this->close(sock,callCloseHandler);
  665. return -1;
  666. }
  667. }
  668. #else // not Windows
  669. long n = (long)::send(sws.sock,data,len,0);
  670. if (n < 0) {
  671. switch(errno) {
  672. #ifdef EAGAIN
  673. case EAGAIN:
  674. #endif
  675. #if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
  676. case EWOULDBLOCK:
  677. #endif
  678. #ifdef EINTR
  679. case EINTR:
  680. #endif
  681. return 0;
  682. default:
  683. this->close(sock,callCloseHandler);
  684. return -1;
  685. }
  686. }
  687. #endif // Windows or not
  688. return n;
  689. }
  690. #ifdef __UNIX_LIKE__
  691. /**
  692. * Attempt to send data to a Unix domain socket connection (non-blocking)
  693. *
  694. * If -1 is returned, the socket should no longer be used as it is now
  695. * destroyed. If callCloseHandler is true, the close handler will be
  696. * called before the function returns.
  697. *
  698. * @param sock An open Unix socket (other socket types will fail)
  699. * @param data Data to send
  700. * @param len Length of data
  701. * @param callCloseHandler If true, call close handler on socket closing failure condition (default: true)
  702. * @return Number of bytes actually sent or -1 on fatal error (socket closure)
  703. */
  704. inline long unixSend(PhySocket *sock,const void *data,unsigned long len,bool callCloseHandler = true)
  705. {
  706. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  707. long n = (long)::write(sws.sock,data,len);
  708. if (n < 0) {
  709. switch(errno) {
  710. #ifdef EAGAIN
  711. case EAGAIN:
  712. #endif
  713. #if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
  714. case EWOULDBLOCK:
  715. #endif
  716. #ifdef EINTR
  717. case EINTR:
  718. #endif
  719. return 0;
  720. default:
  721. this->close(sock,callCloseHandler);
  722. return -1;
  723. }
  724. }
  725. return n;
  726. }
  727. #endif // __UNIX_LIKE__
  728. /**
  729. * For streams, sets whether we want to be notified that the socket is writable
  730. *
  731. * This can be used with TCP, Unix, or socket pair sockets.
  732. *
  733. * Call whack() if this is being done from another thread and you want
  734. * it to take effect immediately. Otherwise it is only guaranteed to
  735. * take effect on the next poll().
  736. *
  737. * @param sock Stream connection socket
  738. * @param notifyWritable Want writable notifications?
  739. */
  740. inline const void setNotifyWritable(PhySocket *sock,bool notifyWritable)
  741. {
  742. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  743. if (notifyWritable) {
  744. FD_SET(sws.sock,&_writefds);
  745. } else {
  746. FD_CLR(sws.sock,&_writefds);
  747. }
  748. }
  749. /**
  750. * Set whether we want to be notified that a socket is readable
  751. *
  752. * This is primarily for raw sockets added with wrapSocket(). It could be
  753. * used with others, but doing so would essentially lock them and prevent
  754. * data from being read from them until this is set to 'true' again.
  755. *
  756. * @param sock Socket to modify
  757. * @param notifyReadable True if socket should be monitored for readability
  758. */
  759. inline const void setNotifyReadable(PhySocket *sock,bool notifyReadable)
  760. {
  761. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  762. if (notifyReadable) {
  763. FD_SET(sws.sock,&_readfds);
  764. } else {
  765. FD_CLR(sws.sock,&_readfds);
  766. }
  767. }
  768. /**
  769. * Wait for activity and handle one or more events
  770. *
  771. * Note that this is not guaranteed to wait up to 'timeout' even
  772. * if nothing happens, as whack() or other events such as signals
  773. * may cause premature termination.
  774. *
  775. * @param timeout Timeout in milliseconds or 0 for none (forever)
  776. */
  777. inline void poll(unsigned long timeout)
  778. {
  779. char buf[131072];
  780. struct sockaddr_storage ss;
  781. struct timeval tv;
  782. fd_set rfds,wfds,efds;
  783. memcpy(&rfds,&_readfds,sizeof(rfds));
  784. memcpy(&wfds,&_writefds,sizeof(wfds));
  785. #if defined(_WIN32) || defined(_WIN64)
  786. memcpy(&efds,&_exceptfds,sizeof(efds));
  787. #else
  788. FD_ZERO(&efds);
  789. #endif
  790. tv.tv_sec = (long)(timeout / 1000);
  791. tv.tv_usec = (long)((timeout % 1000) * 1000);
  792. if (::select((int)_nfds + 1,&rfds,&wfds,&efds,(timeout > 0) ? &tv : (struct timeval *)0) <= 0)
  793. return;
  794. if (FD_ISSET(_whackReceiveSocket,&rfds)) {
  795. char tmp[16];
  796. #if defined(_WIN32) || defined(_WIN64)
  797. ::recv(_whackReceiveSocket,tmp,16,0);
  798. #else
  799. ::read(_whackReceiveSocket,tmp,16);
  800. #endif
  801. }
  802. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();) {
  803. switch (s->type) {
  804. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  805. #if defined(_WIN32) || defined(_WIN64)
  806. if (FD_ISSET(s->sock,&efds)) {
  807. this->close((PhySocket *)&(*s),true);
  808. } else // ... if
  809. #endif
  810. if (FD_ISSET(s->sock,&wfds)) {
  811. socklen_t slen = sizeof(ss);
  812. if (::getpeername(s->sock,(struct sockaddr *)&ss,&slen) != 0) {
  813. this->close((PhySocket *)&(*s),true);
  814. } else {
  815. s->type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  816. FD_SET(s->sock,&_readfds);
  817. FD_CLR(s->sock,&_writefds);
  818. #if defined(_WIN32) || defined(_WIN64)
  819. FD_CLR(s->sock,&_exceptfds);
  820. #endif
  821. try {
  822. _handler->phyOnTcpConnect((PhySocket *)&(*s),&(s->uptr),true);
  823. } catch ( ... ) {}
  824. }
  825. }
  826. break;
  827. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  828. case ZT_PHY_SOCKET_TCP_IN: {
  829. ZT_PHY_SOCKFD_TYPE sock = s->sock; // if closed, s->sock becomes invalid as s is no longer dereferencable
  830. if (FD_ISSET(sock,&rfds)) {
  831. long n = (long)::recv(sock,buf,sizeof(buf),0);
  832. if (n <= 0) {
  833. this->close((PhySocket *)&(*s),true);
  834. } else {
  835. try {
  836. _handler->phyOnTcpData((PhySocket *)&(*s),&(s->uptr),(void *)buf,(unsigned long)n);
  837. } catch ( ... ) {}
  838. }
  839. }
  840. if ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds))) {
  841. try {
  842. _handler->phyOnTcpWritable((PhySocket *)&(*s),&(s->uptr));
  843. } catch ( ... ) {}
  844. }
  845. } break;
  846. case ZT_PHY_SOCKET_TCP_LISTEN:
  847. if (FD_ISSET(s->sock,&rfds)) {
  848. memset(&ss,0,sizeof(ss));
  849. socklen_t slen = sizeof(ss);
  850. ZT_PHY_SOCKFD_TYPE newSock = ::accept(s->sock,(struct sockaddr *)&ss,&slen);
  851. if (ZT_PHY_SOCKFD_VALID(newSock)) {
  852. if (_socks.size() >= ZT_PHY_MAX_SOCKETS) {
  853. ZT_PHY_CLOSE_SOCKET(newSock);
  854. } else {
  855. #if defined(_WIN32) || defined(_WIN64)
  856. { BOOL f = (_noDelay ? TRUE : FALSE); setsockopt(newSock,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  857. { u_long iMode=1; ioctlsocket(newSock,FIONBIO,&iMode); }
  858. #else
  859. { int f = (_noDelay ? 1 : 0); setsockopt(newSock,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  860. fcntl(newSock,F_SETFL,O_NONBLOCK);
  861. #endif
  862. _socks.push_back(PhySocketImpl());
  863. PhySocketImpl &sws = _socks.back();
  864. FD_SET(newSock,&_readfds);
  865. if ((long)newSock > _nfds)
  866. _nfds = (long)newSock;
  867. sws.type = ZT_PHY_SOCKET_TCP_IN;
  868. sws.sock = newSock;
  869. sws.uptr = (void *)0;
  870. memcpy(&(sws.saddr),&ss,sizeof(struct sockaddr_storage));
  871. try {
  872. _handler->phyOnTcpAccept((PhySocket *)&(*s),(PhySocket *)&(_socks.back()),&(s->uptr),&(sws.uptr),(const struct sockaddr *)&(sws.saddr));
  873. } catch ( ... ) {}
  874. }
  875. }
  876. }
  877. break;
  878. case ZT_PHY_SOCKET_UDP:
  879. if (FD_ISSET(s->sock,&rfds)) {
  880. for(;;) {
  881. memset(&ss,0,sizeof(ss));
  882. socklen_t slen = sizeof(ss);
  883. long n = (long)::recvfrom(s->sock,buf,sizeof(buf),0,(struct sockaddr *)&ss,&slen);
  884. if (n > 0) {
  885. try {
  886. _handler->phyOnDatagram((PhySocket *)&(*s),&(s->uptr),(const struct sockaddr *)&(s->saddr),(const struct sockaddr *)&ss,(void *)buf,(unsigned long)n);
  887. } catch ( ... ) {}
  888. } else if (n < 0)
  889. break;
  890. }
  891. }
  892. break;
  893. case ZT_PHY_SOCKET_UNIX_IN: {
  894. #ifdef __UNIX_LIKE__
  895. ZT_PHY_SOCKFD_TYPE sock = s->sock; // if closed, s->sock becomes invalid as s is no longer dereferencable
  896. if ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds))) {
  897. try {
  898. _handler->phyOnUnixWritable((PhySocket *)&(*s),&(s->uptr),false);
  899. } catch ( ... ) {}
  900. }
  901. if (FD_ISSET(sock,&rfds)) {
  902. long n = (long)::read(sock,buf,sizeof(buf));
  903. if (n <= 0) {
  904. this->close((PhySocket *)&(*s),true);
  905. } else {
  906. try {
  907. _handler->phyOnUnixData((PhySocket *)&(*s),&(s->uptr),(void *)buf,(unsigned long)n);
  908. } catch ( ... ) {}
  909. }
  910. }
  911. #endif // __UNIX_LIKE__
  912. } break;
  913. case ZT_PHY_SOCKET_UNIX_LISTEN:
  914. #ifdef __UNIX_LIKE__
  915. if (FD_ISSET(s->sock,&rfds)) {
  916. memset(&ss,0,sizeof(ss));
  917. socklen_t slen = sizeof(ss);
  918. ZT_PHY_SOCKFD_TYPE newSock = ::accept(s->sock,(struct sockaddr *)&ss,&slen);
  919. if (ZT_PHY_SOCKFD_VALID(newSock)) {
  920. if (_socks.size() >= ZT_PHY_MAX_SOCKETS) {
  921. ZT_PHY_CLOSE_SOCKET(newSock);
  922. } else {
  923. fcntl(newSock,F_SETFL,O_NONBLOCK);
  924. _socks.push_back(PhySocketImpl());
  925. PhySocketImpl &sws = _socks.back();
  926. FD_SET(newSock,&_readfds);
  927. if ((long)newSock > _nfds)
  928. _nfds = (long)newSock;
  929. sws.type = ZT_PHY_SOCKET_UNIX_IN;
  930. sws.sock = newSock;
  931. sws.uptr = (void *)0;
  932. memcpy(&(sws.saddr),&ss,sizeof(struct sockaddr_storage));
  933. try {
  934. //_handler->phyOnUnixAccept((PhySocket *)&(*s),(PhySocket *)&(_socks.back()),&(s->uptr),&(sws.uptr));
  935. } catch ( ... ) {}
  936. }
  937. }
  938. }
  939. #endif // __UNIX_LIKE__
  940. break;
  941. case ZT_PHY_SOCKET_FD: {
  942. ZT_PHY_SOCKFD_TYPE sock = s->sock;
  943. const bool readable = ((FD_ISSET(sock,&rfds))&&(FD_ISSET(sock,&_readfds)));
  944. const bool writable = ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds)));
  945. if ((readable)||(writable)) {
  946. try {
  947. //_handler->phyOnFileDescriptorActivity((PhySocket *)&(*s),&(s->uptr),readable,writable);
  948. } catch ( ... ) {}
  949. }
  950. } break;
  951. default:
  952. break;
  953. }
  954. if (s->type == ZT_PHY_SOCKET_CLOSED)
  955. _socks.erase(s++);
  956. else ++s;
  957. }
  958. }
  959. /**
  960. * @param sock Socket to close
  961. * @param callHandlers If true, call handlers for TCP connect (success: false) or close (default: true)
  962. */
  963. inline void close(PhySocket *sock,bool callHandlers = true)
  964. {
  965. if (!sock)
  966. return;
  967. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  968. if (sws.type == ZT_PHY_SOCKET_CLOSED)
  969. return;
  970. FD_CLR(sws.sock,&_readfds);
  971. FD_CLR(sws.sock,&_writefds);
  972. #if defined(_WIN32) || defined(_WIN64)
  973. FD_CLR(sws.sock,&_exceptfds);
  974. #endif
  975. if (sws.type != ZT_PHY_SOCKET_FD)
  976. ZT_PHY_CLOSE_SOCKET(sws.sock);
  977. #ifdef __UNIX_LIKE__
  978. if (sws.type == ZT_PHY_SOCKET_UNIX_LISTEN)
  979. ::unlink(((struct sockaddr_un *)(&(sws.saddr)))->sun_path);
  980. #endif // __UNIX_LIKE__
  981. if (callHandlers) {
  982. switch(sws.type) {
  983. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  984. try {
  985. _handler->phyOnTcpConnect(sock,&(sws.uptr),false);
  986. } catch ( ... ) {}
  987. break;
  988. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  989. case ZT_PHY_SOCKET_TCP_IN:
  990. try {
  991. _handler->phyOnTcpClose(sock,&(sws.uptr));
  992. } catch ( ... ) {}
  993. break;
  994. case ZT_PHY_SOCKET_UNIX_IN:
  995. #ifdef __UNIX_LIKE__
  996. try {
  997. _handler->phyOnUnixClose(sock,&(sws.uptr));
  998. } catch ( ... ) {}
  999. #endif // __UNIX_LIKE__
  1000. break;
  1001. default:
  1002. break;
  1003. }
  1004. }
  1005. // Causes entry to be deleted from list in poll(), ignored elsewhere
  1006. sws.type = ZT_PHY_SOCKET_CLOSED;
  1007. if ((long)sws.sock >= (long)_nfds) {
  1008. long nfds = (long)_whackSendSocket;
  1009. if ((long)_whackReceiveSocket > nfds)
  1010. nfds = (long)_whackReceiveSocket;
  1011. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();++s) {
  1012. if ((s->type != ZT_PHY_SOCKET_CLOSED)&&((long)s->sock > nfds))
  1013. nfds = (long)s->sock;
  1014. }
  1015. _nfds = nfds;
  1016. }
  1017. }
  1018. };
  1019. } // namespace ZeroTier
  1020. #endif