Phy.hpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_PHY_HPP
  27. #define ZT_PHY_HPP
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <list>
  32. #include <stdexcept>
  33. #if defined(_WIN32) || defined(_WIN64)
  34. #include <WinSock2.h>
  35. #include <WS2tcpip.h>
  36. #include <Windows.h>
  37. #define ZT_PHY_SOCKFD_TYPE SOCKET
  38. #define ZT_PHY_SOCKFD_NULL (INVALID_SOCKET)
  39. #define ZT_PHY_SOCKFD_VALID(s) ((s) != INVALID_SOCKET)
  40. #define ZT_PHY_CLOSE_SOCKET(s) ::closesocket(s)
  41. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  42. #define ZT_PHY_MAX_INTERCEPTS ZT_PHY_MAX_SOCKETS
  43. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  44. #else // not Windows
  45. #include <errno.h>
  46. #include <signal.h>
  47. #include <unistd.h>
  48. #include <fcntl.h>
  49. #include <sys/time.h>
  50. #include <sys/types.h>
  51. #include <sys/select.h>
  52. #include <sys/socket.h>
  53. #include <sys/un.h>
  54. #include <arpa/inet.h>
  55. #include <netinet/in.h>
  56. #include <netinet/tcp.h>
  57. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  58. #ifndef IPV6_DONTFRAG
  59. #define IPV6_DONTFRAG 62
  60. #endif
  61. #endif
  62. #define ZT_PHY_SOCKFD_TYPE int
  63. #define ZT_PHY_SOCKFD_NULL (-1)
  64. #define ZT_PHY_SOCKFD_VALID(s) ((s) > -1)
  65. #define ZT_PHY_CLOSE_SOCKET(s) ::close(s)
  66. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  67. #define ZT_PHY_MAX_INTERCEPTS ZT_PHY_MAX_SOCKETS
  68. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  69. #endif // Windows or not
  70. namespace ZeroTier {
  71. /**
  72. * Opaque socket type
  73. */
  74. typedef void PhySocket;
  75. /**
  76. * Simple templated non-blocking sockets implementation
  77. *
  78. * Yes there is boost::asio and libuv, but I like small binaries and I hate
  79. * build dependencies. Both drag in a whole bunch of pasta with them.
  80. *
  81. * This class is templated on a pointer to a handler class which must
  82. * implement the following functions:
  83. *
  84. * For all platforms:
  85. *
  86. * phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  87. * phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  88. * phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  89. * phyOnTcpClose(PhySocket *sock,void **uptr)
  90. * phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  91. * phyOnTcpWritable(PhySocket *sock,void **uptr)
  92. * phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  93. *
  94. * On Linux/OSX/Unix only (not required/used on Windows or elsewhere):
  95. *
  96. * phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  97. * phyOnUnixClose(PhySocket *sock,void **uptr)
  98. * phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  99. * phyOnUnixWritable(PhySocket *sock,void **uptr)
  100. *
  101. * These templates typically refer to function objects. Templates are used to
  102. * avoid the call overhead of indirection, which is surprisingly high for high
  103. * bandwidth applications pushing a lot of packets.
  104. *
  105. * The 'sock' pointer above is an opaque pointer to a socket. Each socket
  106. * has a 'uptr' user-settable/modifiable pointer associated with it, which
  107. * can be set on bind/connect calls and is passed as a void ** to permit
  108. * resetting at any time. The ACCEPT handler takes two sets of sock and
  109. * uptr: sockL and uptrL for the listen socket, and sockN and uptrN for
  110. * the new TCP connection socket that has just been created.
  111. *
  112. * Handlers are always called. On outgoing TCP connection, CONNECT is always
  113. * called on either success or failure followed by DATA and/or WRITABLE as
  114. * indicated. On socket close, handlers are called unless close() is told
  115. * explicitly not to call handlers. It is safe to close a socket within a
  116. * handler, and in that case close() can be told not to call handlers to
  117. * prevent recursion.
  118. *
  119. * This isn't thread-safe with the exception of whack(), which is safe to
  120. * call from another thread to abort poll().
  121. */
  122. template <typename HANDLER_PTR_TYPE>
  123. class Phy
  124. {
  125. private:
  126. HANDLER_PTR_TYPE _handler;
  127. enum PhySocketType
  128. {
  129. ZT_PHY_SOCKET_CLOSED = 0x00, // socket is closed, will be removed on next poll()
  130. ZT_PHY_SOCKET_TCP_OUT_PENDING = 0x01,
  131. ZT_PHY_SOCKET_TCP_OUT_CONNECTED = 0x02,
  132. ZT_PHY_SOCKET_TCP_IN = 0x03,
  133. ZT_PHY_SOCKET_TCP_LISTEN = 0x04,
  134. ZT_PHY_SOCKET_UDP = 0x05,
  135. ZT_PHY_SOCKET_FD = 0x06,
  136. ZT_PHY_SOCKET_UNIX_IN = 0x07,
  137. ZT_PHY_SOCKET_UNIX_LISTEN = 0x08
  138. };
  139. struct PhySocketImpl
  140. {
  141. PhySocketType type;
  142. ZT_PHY_SOCKFD_TYPE sock;
  143. void *uptr; // user-settable pointer
  144. ZT_PHY_SOCKADDR_STORAGE_TYPE saddr; // remote for TCP_OUT and TCP_IN, local for TCP_LISTEN, RAW, and UDP
  145. };
  146. std::list<PhySocketImpl> _socks;
  147. fd_set _readfds;
  148. fd_set _writefds;
  149. #if defined(_WIN32) || defined(_WIN64)
  150. fd_set _exceptfds;
  151. #endif
  152. long _nfds;
  153. ZT_PHY_SOCKFD_TYPE _whackReceiveSocket;
  154. ZT_PHY_SOCKFD_TYPE _whackSendSocket;
  155. bool _noDelay;
  156. bool _noCheck;
  157. public:
  158. /**
  159. * @param handler Pointer of type HANDLER_PTR_TYPE to handler
  160. * @param noDelay If true, disable TCP NAGLE algorithm on TCP sockets
  161. * @param noCheck If true, attempt to set UDP SO_NO_CHECK option to disable sending checksums
  162. */
  163. Phy(HANDLER_PTR_TYPE handler,bool noDelay,bool noCheck) :
  164. _handler(handler)
  165. {
  166. FD_ZERO(&_readfds);
  167. FD_ZERO(&_writefds);
  168. #if defined(_WIN32) || defined(_WIN64)
  169. FD_ZERO(&_exceptfds);
  170. SOCKET pipes[2];
  171. { // hack copied from StackOverflow, behaves a bit like pipe() on *nix systems
  172. struct sockaddr_in inaddr;
  173. struct sockaddr addr;
  174. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  175. if (lst == INVALID_SOCKET)
  176. throw std::runtime_error("unable to create pipes for select() abort");
  177. memset(&inaddr, 0, sizeof(inaddr));
  178. memset(&addr, 0, sizeof(addr));
  179. inaddr.sin_family = AF_INET;
  180. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  181. inaddr.sin_port = 0;
  182. int yes=1;
  183. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  184. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  185. listen(lst,1);
  186. int len=sizeof(inaddr);
  187. getsockname(lst, &addr,&len);
  188. pipes[0]=::socket(AF_INET, SOCK_STREAM,0);
  189. if (pipes[0] == INVALID_SOCKET)
  190. throw std::runtime_error("unable to create pipes for select() abort");
  191. connect(pipes[0],&addr,len);
  192. pipes[1]=accept(lst,0,0);
  193. closesocket(lst);
  194. }
  195. #else // not Windows
  196. int pipes[2];
  197. if (::pipe(pipes))
  198. throw std::runtime_error("unable to create pipes for select() abort");
  199. #endif // Windows or not
  200. _nfds = (pipes[0] > pipes[1]) ? (long)pipes[0] : (long)pipes[1];
  201. _whackReceiveSocket = pipes[0];
  202. _whackSendSocket = pipes[1];
  203. _noDelay = noDelay;
  204. _noCheck = noCheck;
  205. }
  206. ~Phy()
  207. {
  208. for(typename std::list<PhySocketImpl>::const_iterator s(_socks.begin());s!=_socks.end();++s) {
  209. if (s->type != ZT_PHY_SOCKET_CLOSED)
  210. this->close((PhySocket *)&(*s),true);
  211. }
  212. ZT_PHY_CLOSE_SOCKET(_whackReceiveSocket);
  213. ZT_PHY_CLOSE_SOCKET(_whackSendSocket);
  214. }
  215. /**
  216. * @param s Socket object
  217. * @return Underlying OS-type (usually int or long) file descriptor associated with object
  218. */
  219. static inline ZT_PHY_SOCKFD_TYPE getDescriptor(PhySocket *s) throw() { return reinterpret_cast<PhySocketImpl *>(s)->sock; }
  220. /**
  221. * @param s Socket object
  222. * @return Pointer to user object
  223. */
  224. static inline void** getuptr(PhySocket *s) throw() { return &(reinterpret_cast<PhySocketImpl *>(s)->uptr); }
  225. /**
  226. * Cause poll() to stop waiting immediately
  227. *
  228. * This can be used to reset the polling loop after changes that require
  229. * attention, or to shut down a background thread that is waiting, etc.
  230. */
  231. inline void whack()
  232. {
  233. #if defined(_WIN32) || defined(_WIN64)
  234. ::send(_whackSendSocket,(const char *)this,1,0);
  235. #else
  236. (void)(::write(_whackSendSocket,(PhySocket *)this,1));
  237. #endif
  238. }
  239. /**
  240. * @return Number of open sockets
  241. */
  242. inline unsigned long count() const throw() { return _socks.size(); }
  243. /**
  244. * @return Maximum number of sockets allowed
  245. */
  246. inline unsigned long maxCount() const throw() { return ZT_PHY_MAX_SOCKETS; }
  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 -= 16384;
  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 -= 16384;
  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. 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);
  416. #else
  417. return ((long)::sendto(sws.sock,data,len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  418. #endif
  419. }
  420. #ifdef __UNIX_LIKE__
  421. /**
  422. * Listen for connections on a Unix domain socket
  423. *
  424. * @param path Path to Unix domain socket
  425. * @param uptr Arbitrary pointer to associate
  426. * @return PhySocket or NULL if cannot bind
  427. */
  428. inline PhySocket *unixListen(const char *path,void *uptr = (void *)0)
  429. {
  430. struct sockaddr_un sun;
  431. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  432. return (PhySocket *)0;
  433. memset(&sun,0,sizeof(sun));
  434. sun.sun_family = AF_UNIX;
  435. if (strlen(path) >= sizeof(sun.sun_path))
  436. return (PhySocket *)0;
  437. strcpy(sun.sun_path,path);
  438. ZT_PHY_SOCKFD_TYPE s = ::socket(PF_UNIX,SOCK_STREAM,0);
  439. if (!ZT_PHY_SOCKFD_VALID(s))
  440. return (PhySocket *)0;
  441. ::fcntl(s,F_SETFL,O_NONBLOCK);
  442. ::unlink(path);
  443. if (::bind(s,(struct sockaddr *)&sun,sizeof(struct sockaddr_un)) != 0) {
  444. ZT_PHY_CLOSE_SOCKET(s);
  445. return (PhySocket *)0;
  446. }
  447. if (::listen(s,128) != 0) {
  448. ZT_PHY_CLOSE_SOCKET(s);
  449. return (PhySocket *)0;
  450. }
  451. try {
  452. _socks.push_back(PhySocketImpl());
  453. } catch ( ... ) {
  454. ZT_PHY_CLOSE_SOCKET(s);
  455. return (PhySocket *)0;
  456. }
  457. PhySocketImpl &sws = _socks.back();
  458. if ((long)s > _nfds)
  459. _nfds = (long)s;
  460. FD_SET(s,&_readfds);
  461. sws.type = ZT_PHY_SOCKET_UNIX_LISTEN;
  462. sws.sock = s;
  463. sws.uptr = uptr;
  464. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  465. memcpy(&(sws.saddr),&sun,sizeof(struct sockaddr_un));
  466. return (PhySocket *)&sws;
  467. }
  468. #endif // __UNIX_LIKE__
  469. /**
  470. * Bind a local listen socket to listen for new TCP connections
  471. *
  472. * @param localAddress Local address and port
  473. * @param uptr Initial value of uptr for new socket (default: NULL)
  474. * @return Socket or NULL on failure to bind
  475. */
  476. inline PhySocket *tcpListen(const struct sockaddr *localAddress,void *uptr = (void *)0)
  477. {
  478. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  479. return (PhySocket *)0;
  480. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_STREAM,0);
  481. if (!ZT_PHY_SOCKFD_VALID(s))
  482. return (PhySocket *)0;
  483. #if defined(_WIN32) || defined(_WIN64)
  484. {
  485. BOOL f;
  486. f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  487. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  488. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  489. u_long iMode=1;
  490. ioctlsocket(s,FIONBIO,&iMode);
  491. }
  492. #else
  493. {
  494. int f;
  495. f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  496. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  497. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  498. fcntl(s,F_SETFL,O_NONBLOCK);
  499. }
  500. #endif
  501. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  502. ZT_PHY_CLOSE_SOCKET(s);
  503. return (PhySocket *)0;
  504. }
  505. if (::listen(s,1024)) {
  506. ZT_PHY_CLOSE_SOCKET(s);
  507. return (PhySocket *)0;
  508. }
  509. try {
  510. _socks.push_back(PhySocketImpl());
  511. } catch ( ... ) {
  512. ZT_PHY_CLOSE_SOCKET(s);
  513. return (PhySocket *)0;
  514. }
  515. PhySocketImpl &sws = _socks.back();
  516. if ((long)s > _nfds)
  517. _nfds = (long)s;
  518. FD_SET(s,&_readfds);
  519. sws.type = ZT_PHY_SOCKET_TCP_LISTEN;
  520. sws.sock = s;
  521. sws.uptr = uptr;
  522. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  523. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  524. return (PhySocket *)&sws;
  525. }
  526. /**
  527. * Start a non-blocking connect; CONNECT handler is called on success or failure
  528. *
  529. * A return value of NULL indicates a synchronous failure such as a
  530. * failure to open a socket. The TCP connection handler is not called
  531. * in this case.
  532. *
  533. * It is possible on some platforms for an "instant connect" to occur,
  534. * such as when connecting to a loopback address. In this case, the
  535. * 'connected' result parameter will be set to 'true' and if the
  536. * 'callConnectHandler' flag is true (the default) the TCP connect
  537. * handler will be called before the function returns.
  538. *
  539. * These semantics can be a bit confusing, but they're less so than
  540. * the underlying semantics of asynchronous TCP connect.
  541. *
  542. * @param remoteAddress Remote address
  543. * @param connected Result parameter: set to whether an "instant connect" has occurred (true if yes)
  544. * @param uptr Initial value of uptr for new socket (default: NULL)
  545. * @param callConnectHandler If true, call TCP connect handler even if result is known before function exit (default: true)
  546. * @return New socket or NULL on failure
  547. */
  548. inline PhySocket *tcpConnect(const struct sockaddr *remoteAddress,bool &connected,void *uptr = (void *)0,bool callConnectHandler = true)
  549. {
  550. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  551. return (PhySocket *)0;
  552. ZT_PHY_SOCKFD_TYPE s = ::socket(remoteAddress->sa_family,SOCK_STREAM,0);
  553. if (!ZT_PHY_SOCKFD_VALID(s)) {
  554. connected = false;
  555. return (PhySocket *)0;
  556. }
  557. #if defined(_WIN32) || defined(_WIN64)
  558. {
  559. BOOL f;
  560. if (remoteAddress->sa_family == AF_INET6) { f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f)); }
  561. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  562. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  563. u_long iMode=1;
  564. ioctlsocket(s,FIONBIO,&iMode);
  565. }
  566. #else
  567. {
  568. int f;
  569. if (remoteAddress->sa_family == AF_INET6) { f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f)); }
  570. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  571. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  572. fcntl(s,F_SETFL,O_NONBLOCK);
  573. }
  574. #endif
  575. connected = true;
  576. if (::connect(s,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  577. connected = false;
  578. #if defined(_WIN32) || defined(_WIN64)
  579. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  580. #else
  581. if (errno != EINPROGRESS) {
  582. #endif
  583. ZT_PHY_CLOSE_SOCKET(s);
  584. return (PhySocket *)0;
  585. } // else connection is proceeding asynchronously...
  586. }
  587. try {
  588. _socks.push_back(PhySocketImpl());
  589. } catch ( ... ) {
  590. ZT_PHY_CLOSE_SOCKET(s);
  591. return (PhySocket *)0;
  592. }
  593. PhySocketImpl &sws = _socks.back();
  594. if ((long)s > _nfds)
  595. _nfds = (long)s;
  596. if (connected) {
  597. FD_SET(s,&_readfds);
  598. sws.type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  599. } else {
  600. FD_SET(s,&_writefds);
  601. #if defined(_WIN32) || defined(_WIN64)
  602. FD_SET(s,&_exceptfds);
  603. #endif
  604. sws.type = ZT_PHY_SOCKET_TCP_OUT_PENDING;
  605. }
  606. sws.sock = s;
  607. sws.uptr = uptr;
  608. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  609. memcpy(&(sws.saddr),remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  610. if ((callConnectHandler)&&(connected)) {
  611. try {
  612. _handler->phyOnTcpConnect((PhySocket *)&sws,&(sws.uptr),true);
  613. } catch ( ... ) {}
  614. }
  615. return (PhySocket *)&sws;
  616. }
  617. /**
  618. * Try to set buffer sizes as close to the given value as possible
  619. *
  620. * This will try the specified value and then lower values in 16K increments
  621. * until one works.
  622. *
  623. * @param sock Socket
  624. * @param bufferSize Desired buffer sizes
  625. */
  626. inline void setBufferSizes(const PhySocket *sock,int bufferSize)
  627. {
  628. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  629. if (bufferSize > 0) {
  630. int bs = bufferSize;
  631. while (bs >= 65536) {
  632. int tmpbs = bs;
  633. if (::setsockopt(sws.sock,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  634. break;
  635. bs -= 16384;
  636. }
  637. bs = bufferSize;
  638. while (bs >= 65536) {
  639. int tmpbs = bs;
  640. if (::setsockopt(sws.sock,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  641. break;
  642. bs -= 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 const 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 const 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(;;) {
  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),false);
  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