Phy.hpp 35 KB

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