2
0

Phy.hpp 35 KB

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