Phy.hpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156
  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() { memset(ifname, 0, sizeof(ifname)); }
  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. char ifname[256 + 4];
  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. * @param s Socket object
  221. * @param nameBuf Buffer to store name of interface which this Socket object is bound to
  222. * @param buflen Length of buffer to copy name into
  223. */
  224. static inline void getIfName(PhySocket* s, char* nameBuf, int buflen)
  225. {
  226. PhySocketImpl& sws = *(reinterpret_cast<PhySocketImpl*>(s));
  227. if (sws.type == ZT_PHY_SOCKET_CLOSED) {
  228. return;
  229. }
  230. if (s) {
  231. memcpy(nameBuf, reinterpret_cast<PhySocketImpl*>(s)->ifname, buflen);
  232. }
  233. }
  234. /**
  235. * @param s Socket object
  236. * @param ifname Buffer containing name of interface that this Socket object is bound to
  237. * @param len Length of name of interface
  238. */
  239. static inline void setIfName(PhySocket* s, char* ifname, int len)
  240. {
  241. PhySocketImpl& sws = *(reinterpret_cast<PhySocketImpl*>(s));
  242. if (sws.type == ZT_PHY_SOCKET_CLOSED) {
  243. return;
  244. }
  245. if (s) {
  246. memcpy(&(reinterpret_cast<PhySocketImpl*>(s)->ifname), ifname, len);
  247. }
  248. }
  249. /**
  250. * Cause poll() to stop waiting immediately
  251. *
  252. * This can be used to reset the polling loop after changes that require
  253. * attention, or to shut down a background thread that is waiting, etc.
  254. */
  255. inline void whack()
  256. {
  257. #if defined(_WIN32) || defined(_WIN64)
  258. ::send(_whackSendSocket, (const char*)this, 1, 0);
  259. #else
  260. (void)(::write(_whackSendSocket, (PhySocket*)this, 1));
  261. #endif
  262. }
  263. /**
  264. * @return Number of open sockets
  265. */
  266. inline unsigned long count() const throw()
  267. {
  268. return _socks.size();
  269. }
  270. /**
  271. * @return Maximum number of sockets allowed
  272. */
  273. inline unsigned long maxCount() const throw()
  274. {
  275. return ZT_PHY_MAX_SOCKETS;
  276. }
  277. /**
  278. * Wrap a raw file descriptor in a PhySocket structure
  279. *
  280. * This can be used to select/poll on a raw file descriptor as part of this
  281. * class's I/O loop. By default the fd is set for read notification but
  282. * this can be controlled with setNotifyReadable(). When any detected
  283. * condition is present, the phyOnFileDescriptorActivity() callback is
  284. * called with one or both of its arguments 'true'.
  285. *
  286. * The Phy<>::close() method *must* be called when you're done with this
  287. * file descriptor to remove it from the select/poll set, but unlike other
  288. * types of sockets Phy<> does not actually close the underlying fd or
  289. * otherwise manage its life cycle. There is also no close notification
  290. * callback for this fd, since Phy<> doesn't actually perform reading or
  291. * writing or detect error conditions. This is only useful for adding a
  292. * file descriptor to Phy<> to select/poll on it.
  293. *
  294. * @param fd Raw file descriptor
  295. * @param uptr User pointer to supply to callbacks
  296. * @return PhySocket wrapping fd or NULL on failure (out of memory or too many sockets)
  297. */
  298. inline PhySocket *wrapSocket(ZT_PHY_SOCKFD_TYPE fd,void *uptr = (void *)0)
  299. {
  300. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  301. return (PhySocket *)0;
  302. try {
  303. _socks.push_back(PhySocketImpl());
  304. } catch ( ... ) {
  305. return (PhySocket *)0;
  306. }
  307. PhySocketImpl &sws = _socks.back();
  308. if ((long)fd > _nfds)
  309. _nfds = (long)fd;
  310. FD_SET(fd,&_readfds);
  311. sws.type = ZT_PHY_SOCKET_UNIX_IN; /* TODO: Type was changed to allow for CBs with new RPC model */
  312. sws.sock = fd;
  313. sws.uptr = uptr;
  314. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  315. // no sockaddr for this socket type, leave saddr null
  316. return (PhySocket *)&sws;
  317. }
  318. /**
  319. * Bind a UDP socket
  320. *
  321. * @param localAddress Local endpoint address and port
  322. * @param uptr Initial value of user pointer associated with this socket (default: NULL)
  323. * @param bufferSize Desired socket receive/send buffer size -- will set as close to this as possible (default: 0, leave alone)
  324. * @return Socket or NULL on failure to bind
  325. */
  326. inline PhySocket *udpBind(const struct sockaddr *localAddress,void *uptr = (void *)0,int bufferSize = 0)
  327. {
  328. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  329. return (PhySocket *)0;
  330. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_DGRAM,0);
  331. if (!ZT_PHY_SOCKFD_VALID(s))
  332. return (PhySocket *)0;
  333. if (bufferSize > 0) {
  334. int bs = bufferSize;
  335. while (bs >= 65536) {
  336. int tmpbs = bs;
  337. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  338. break;
  339. bs -= 4096;
  340. }
  341. bs = bufferSize;
  342. while (bs >= 65536) {
  343. int tmpbs = bs;
  344. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  345. break;
  346. bs -= 4096;
  347. }
  348. }
  349. #if defined(_WIN32) || defined(_WIN64)
  350. {
  351. BOOL f;
  352. if (localAddress->sa_family == AF_INET6) {
  353. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  354. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  355. }
  356. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  357. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  358. }
  359. #else // not Windows
  360. {
  361. int f;
  362. if (localAddress->sa_family == AF_INET6) {
  363. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  364. #ifdef IPV6_MTU_DISCOVER
  365. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  366. #endif
  367. #ifdef IPV6_DONTFRAG
  368. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  369. #endif
  370. }
  371. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  372. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  373. #ifdef IP_DONTFRAG
  374. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  375. #endif
  376. #ifdef IP_MTU_DISCOVER
  377. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  378. #endif
  379. #ifdef SO_NO_CHECK
  380. // For now at least we only set SO_NO_CHECK on IPv4 sockets since some
  381. // IPv6 stacks incorrectly discard zero checksum packets. May remove
  382. // this restriction later once broken stuff dies more.
  383. if ((localAddress->sa_family == AF_INET)&&(_noCheck)) {
  384. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  385. }
  386. #endif
  387. }
  388. #endif // Windows or not
  389. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  390. ZT_PHY_CLOSE_SOCKET(s);
  391. return (PhySocket *)0;
  392. }
  393. #if defined(_WIN32) || defined(_WIN64)
  394. { u_long iMode=1; ioctlsocket(s,FIONBIO,&iMode); }
  395. #else
  396. fcntl(s,F_SETFL,O_NONBLOCK);
  397. #endif
  398. try {
  399. _socks.push_back(PhySocketImpl());
  400. } catch ( ... ) {
  401. ZT_PHY_CLOSE_SOCKET(s);
  402. return (PhySocket *)0;
  403. }
  404. PhySocketImpl &sws = _socks.back();
  405. if ((long)s > _nfds)
  406. _nfds = (long)s;
  407. FD_SET(s,&_readfds);
  408. sws.type = ZT_PHY_SOCKET_UDP;
  409. sws.sock = s;
  410. sws.uptr = uptr;
  411. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  412. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  413. return (PhySocket *)&sws;
  414. }
  415. /**
  416. * Set the IP TTL for the next outgoing packet (for IPv4 UDP sockets only)
  417. *
  418. * @param ttl New TTL (0 or >255 will set it to 255)
  419. * @return True on success
  420. */
  421. inline bool setIp4UdpTtl(PhySocket *sock,unsigned int ttl)
  422. {
  423. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  424. #if defined(_WIN32) || defined(_WIN64)
  425. DWORD tmp = ((ttl == 0)||(ttl > 255)) ? 255 : (DWORD)ttl;
  426. return (::setsockopt(sws.sock,IPPROTO_IP,IP_TTL,(const char *)&tmp,sizeof(tmp)) == 0);
  427. #else
  428. int tmp = ((ttl == 0)||(ttl > 255)) ? 255 : (int)ttl;
  429. return (::setsockopt(sws.sock,IPPROTO_IP,IP_TTL,(void *)&tmp,sizeof(tmp)) == 0);
  430. #endif
  431. }
  432. /**
  433. * Send a UDP packet
  434. *
  435. * @param sock UDP socket
  436. * @param remoteAddress Destination address (must be correct type for socket)
  437. * @param data Data to send
  438. * @param len Length of packet
  439. * @return True if packet appears to have been sent successfully
  440. */
  441. inline bool udpSend(PhySocket *sock,const struct sockaddr *remoteAddress,const void *data,unsigned long len)
  442. {
  443. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  444. #if defined(_WIN32) || defined(_WIN64)
  445. 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);
  446. #else
  447. return ((long)::sendto(sws.sock,data,len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  448. #endif
  449. }
  450. #ifdef __UNIX_LIKE__
  451. /**
  452. * Listen for connections on a Unix domain socket
  453. *
  454. * @param path Path to Unix domain socket
  455. * @param uptr Arbitrary pointer to associate
  456. * @return PhySocket or NULL if cannot bind
  457. */
  458. inline PhySocket *unixListen(const char *path,void *uptr = (void *)0)
  459. {
  460. struct sockaddr_un sun;
  461. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  462. return (PhySocket *)0;
  463. memset(&sun,0,sizeof(sun));
  464. sun.sun_family = AF_UNIX;
  465. if (strlen(path) >= sizeof(sun.sun_path))
  466. return (PhySocket *)0;
  467. strcpy(sun.sun_path,path);
  468. ZT_PHY_SOCKFD_TYPE s = ::socket(PF_UNIX,SOCK_STREAM,0);
  469. if (!ZT_PHY_SOCKFD_VALID(s))
  470. return (PhySocket *)0;
  471. ::fcntl(s,F_SETFL,O_NONBLOCK);
  472. ::unlink(path);
  473. if (::bind(s,(struct sockaddr *)&sun,sizeof(struct sockaddr_un)) != 0) {
  474. ZT_PHY_CLOSE_SOCKET(s);
  475. return (PhySocket *)0;
  476. }
  477. if (::listen(s,128) != 0) {
  478. ZT_PHY_CLOSE_SOCKET(s);
  479. return (PhySocket *)0;
  480. }
  481. try {
  482. _socks.push_back(PhySocketImpl());
  483. } catch ( ... ) {
  484. ZT_PHY_CLOSE_SOCKET(s);
  485. return (PhySocket *)0;
  486. }
  487. PhySocketImpl &sws = _socks.back();
  488. if ((long)s > _nfds)
  489. _nfds = (long)s;
  490. FD_SET(s,&_readfds);
  491. sws.type = ZT_PHY_SOCKET_UNIX_LISTEN;
  492. sws.sock = s;
  493. sws.uptr = uptr;
  494. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  495. memcpy(&(sws.saddr),&sun,sizeof(struct sockaddr_un));
  496. return (PhySocket *)&sws;
  497. }
  498. #endif // __UNIX_LIKE__
  499. /**
  500. * Bind a local listen socket to listen for new TCP connections
  501. *
  502. * @param localAddress Local address and port
  503. * @param uptr Initial value of uptr for new socket (default: NULL)
  504. * @return Socket or NULL on failure to bind
  505. */
  506. inline PhySocket *tcpListen(const struct sockaddr *localAddress,void *uptr = (void *)0)
  507. {
  508. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  509. return (PhySocket *)0;
  510. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_STREAM,0);
  511. if (!ZT_PHY_SOCKFD_VALID(s))
  512. return (PhySocket *)0;
  513. #if defined(_WIN32) || defined(_WIN64)
  514. {
  515. BOOL f;
  516. f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  517. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  518. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  519. u_long iMode=1;
  520. ioctlsocket(s,FIONBIO,&iMode);
  521. }
  522. #else
  523. {
  524. int f;
  525. f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  526. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  527. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  528. fcntl(s,F_SETFL,O_NONBLOCK);
  529. }
  530. #endif
  531. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  532. ZT_PHY_CLOSE_SOCKET(s);
  533. return (PhySocket *)0;
  534. }
  535. if (::listen(s,1024)) {
  536. ZT_PHY_CLOSE_SOCKET(s);
  537. return (PhySocket *)0;
  538. }
  539. try {
  540. _socks.push_back(PhySocketImpl());
  541. } catch ( ... ) {
  542. ZT_PHY_CLOSE_SOCKET(s);
  543. return (PhySocket *)0;
  544. }
  545. PhySocketImpl &sws = _socks.back();
  546. if ((long)s > _nfds)
  547. _nfds = (long)s;
  548. FD_SET(s,&_readfds);
  549. sws.type = ZT_PHY_SOCKET_TCP_LISTEN;
  550. sws.sock = s;
  551. sws.uptr = uptr;
  552. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  553. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  554. return (PhySocket *)&sws;
  555. }
  556. /**
  557. * Start a non-blocking connect; CONNECT handler is called on success or failure
  558. *
  559. * A return value of NULL indicates a synchronous failure such as a
  560. * failure to open a socket. The TCP connection handler is not called
  561. * in this case.
  562. *
  563. * It is possible on some platforms for an "instant connect" to occur,
  564. * such as when connecting to a loopback address. In this case, the
  565. * 'connected' result parameter will be set to 'true' and if the
  566. * 'callConnectHandler' flag is true (the default) the TCP connect
  567. * handler will be called before the function returns.
  568. *
  569. * These semantics can be a bit confusing, but they're less so than
  570. * the underlying semantics of asynchronous TCP connect.
  571. *
  572. * @param remoteAddress Remote address
  573. * @param connected Result parameter: set to whether an "instant connect" has occurred (true if yes)
  574. * @param uptr Initial value of uptr for new socket (default: NULL)
  575. * @param callConnectHandler If true, call TCP connect handler even if result is known before function exit (default: true)
  576. * @return New socket or NULL on failure
  577. */
  578. inline PhySocket *tcpConnect(const struct sockaddr *remoteAddress,bool &connected,void *uptr = (void *)0,bool callConnectHandler = true)
  579. {
  580. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  581. return (PhySocket *)0;
  582. ZT_PHY_SOCKFD_TYPE s = ::socket(remoteAddress->sa_family,SOCK_STREAM,0);
  583. if (!ZT_PHY_SOCKFD_VALID(s)) {
  584. connected = false;
  585. return (PhySocket *)0;
  586. }
  587. #if defined(_WIN32) || defined(_WIN64)
  588. {
  589. BOOL f;
  590. if (remoteAddress->sa_family == AF_INET6) { f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f)); }
  591. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  592. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  593. u_long iMode=1;
  594. ioctlsocket(s,FIONBIO,&iMode);
  595. }
  596. #else
  597. {
  598. int f;
  599. if (remoteAddress->sa_family == AF_INET6) { f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f)); }
  600. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  601. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  602. fcntl(s,F_SETFL,O_NONBLOCK);
  603. }
  604. #endif
  605. connected = true;
  606. if (::connect(s,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  607. connected = false;
  608. #if defined(_WIN32) || defined(_WIN64)
  609. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  610. #else
  611. if (errno != EINPROGRESS) {
  612. #endif
  613. ZT_PHY_CLOSE_SOCKET(s);
  614. return (PhySocket *)0;
  615. } // else connection is proceeding asynchronously...
  616. }
  617. try {
  618. _socks.push_back(PhySocketImpl());
  619. } catch ( ... ) {
  620. ZT_PHY_CLOSE_SOCKET(s);
  621. return (PhySocket *)0;
  622. }
  623. PhySocketImpl &sws = _socks.back();
  624. if ((long)s > _nfds)
  625. _nfds = (long)s;
  626. if (connected) {
  627. FD_SET(s,&_readfds);
  628. sws.type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  629. } else {
  630. FD_SET(s,&_writefds);
  631. #if defined(_WIN32) || defined(_WIN64)
  632. FD_SET(s,&_exceptfds);
  633. #endif
  634. sws.type = ZT_PHY_SOCKET_TCP_OUT_PENDING;
  635. }
  636. sws.sock = s;
  637. sws.uptr = uptr;
  638. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  639. memcpy(&(sws.saddr),remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  640. if ((callConnectHandler)&&(connected)) {
  641. try {
  642. _handler->phyOnTcpConnect((PhySocket *)&sws,&(sws.uptr),true);
  643. } catch ( ... ) {}
  644. }
  645. return (PhySocket *)&sws;
  646. }
  647. /**
  648. * Try to set buffer sizes as close to the given value as possible
  649. *
  650. * This will try the specified value and then lower values in 16K increments
  651. * until one works.
  652. *
  653. * @param sock Socket
  654. * @param receiveBufferSize Desired size of receive buffer
  655. * @param sendBufferSize Desired size of send buffer
  656. */
  657. inline void setBufferSizes(const PhySocket *sock,int receiveBufferSize,int sendBufferSize)
  658. {
  659. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  660. if (receiveBufferSize > 0) {
  661. while (receiveBufferSize > 0) {
  662. int tmpbs = receiveBufferSize;
  663. if (::setsockopt(sws.sock,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  664. break;
  665. receiveBufferSize -= 16384;
  666. }
  667. }
  668. if (sendBufferSize > 0) {
  669. while (sendBufferSize > 0) {
  670. int tmpbs = sendBufferSize;
  671. if (::setsockopt(sws.sock,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  672. break;
  673. sendBufferSize -= 16384;
  674. }
  675. }
  676. }
  677. /**
  678. * Attempt to send data to a stream socket (non-blocking)
  679. *
  680. * If -1 is returned, the socket should no longer be used as it is now
  681. * destroyed. If callCloseHandler is true, the close handler will be
  682. * called before the function returns.
  683. *
  684. * This can be used with TCP, Unix, or socket pair sockets.
  685. *
  686. * @param sock An open stream socket (other socket types will fail)
  687. * @param data Data to send
  688. * @param len Length of data
  689. * @param callCloseHandler If true, call close handler on socket closing failure condition (default: true)
  690. * @return Number of bytes actually sent or -1 on fatal error (socket closure)
  691. */
  692. inline long streamSend(PhySocket *sock,const void *data,unsigned long len,bool callCloseHandler = true)
  693. {
  694. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  695. #if defined(_WIN32) || defined(_WIN64)
  696. long n = (long)::send(sws.sock,reinterpret_cast<const char *>(data),len,0);
  697. if (n == SOCKET_ERROR) {
  698. switch(WSAGetLastError()) {
  699. case WSAEINTR:
  700. case WSAEWOULDBLOCK:
  701. return 0;
  702. default:
  703. this->close(sock,callCloseHandler);
  704. return -1;
  705. }
  706. }
  707. #else // not Windows
  708. long n = (long)::send(sws.sock,data,len,0);
  709. if (n < 0) {
  710. switch(errno) {
  711. #ifdef EAGAIN
  712. case EAGAIN:
  713. #endif
  714. #if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
  715. case EWOULDBLOCK:
  716. #endif
  717. #ifdef EINTR
  718. case EINTR:
  719. #endif
  720. return 0;
  721. default:
  722. this->close(sock,callCloseHandler);
  723. return -1;
  724. }
  725. }
  726. #endif // Windows or not
  727. return n;
  728. }
  729. #ifdef __UNIX_LIKE__
  730. /**
  731. * Attempt to send data to a Unix domain socket connection (non-blocking)
  732. *
  733. * If -1 is returned, the socket should no longer be used as it is now
  734. * destroyed. If callCloseHandler is true, the close handler will be
  735. * called before the function returns.
  736. *
  737. * @param sock An open Unix socket (other socket types will fail)
  738. * @param data Data to send
  739. * @param len Length of data
  740. * @param callCloseHandler If true, call close handler on socket closing failure condition (default: true)
  741. * @return Number of bytes actually sent or -1 on fatal error (socket closure)
  742. */
  743. inline long unixSend(PhySocket *sock,const void *data,unsigned long len,bool callCloseHandler = true)
  744. {
  745. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  746. long n = (long)::write(sws.sock,data,len);
  747. if (n < 0) {
  748. switch(errno) {
  749. #ifdef EAGAIN
  750. case EAGAIN:
  751. #endif
  752. #if defined(EWOULDBLOCK) && ( !defined(EAGAIN) || (EWOULDBLOCK != EAGAIN) )
  753. case EWOULDBLOCK:
  754. #endif
  755. #ifdef EINTR
  756. case EINTR:
  757. #endif
  758. return 0;
  759. default:
  760. this->close(sock,callCloseHandler);
  761. return -1;
  762. }
  763. }
  764. return n;
  765. }
  766. #endif // __UNIX_LIKE__
  767. /**
  768. * For streams, sets whether we want to be notified that the socket is writable
  769. *
  770. * This can be used with TCP, Unix, or socket pair sockets.
  771. *
  772. * Call whack() if this is being done from another thread and you want
  773. * it to take effect immediately. Otherwise it is only guaranteed to
  774. * take effect on the next poll().
  775. *
  776. * @param sock Stream connection socket
  777. * @param notifyWritable Want writable notifications?
  778. */
  779. inline void setNotifyWritable(PhySocket *sock,bool notifyWritable)
  780. {
  781. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  782. if (notifyWritable) {
  783. FD_SET(sws.sock,&_writefds);
  784. } else {
  785. FD_CLR(sws.sock,&_writefds);
  786. }
  787. }
  788. /**
  789. * Set whether we want to be notified that a socket is readable
  790. *
  791. * This is primarily for raw sockets added with wrapSocket(). It could be
  792. * used with others, but doing so would essentially lock them and prevent
  793. * data from being read from them until this is set to 'true' again.
  794. *
  795. * @param sock Socket to modify
  796. * @param notifyReadable True if socket should be monitored for readability
  797. */
  798. inline void setNotifyReadable(PhySocket *sock,bool notifyReadable)
  799. {
  800. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  801. if (notifyReadable) {
  802. FD_SET(sws.sock,&_readfds);
  803. } else {
  804. FD_CLR(sws.sock,&_readfds);
  805. }
  806. }
  807. /**
  808. * Wait for activity and handle one or more events
  809. *
  810. * Note that this is not guaranteed to wait up to 'timeout' even
  811. * if nothing happens, as whack() or other events such as signals
  812. * may cause premature termination.
  813. *
  814. * @param timeout Timeout in milliseconds or 0 for none (forever)
  815. */
  816. inline void poll(unsigned long timeout)
  817. {
  818. char buf[131072];
  819. struct sockaddr_storage ss;
  820. struct timeval tv;
  821. fd_set rfds,wfds,efds;
  822. memcpy(&rfds,&_readfds,sizeof(rfds));
  823. memcpy(&wfds,&_writefds,sizeof(wfds));
  824. #if defined(_WIN32) || defined(_WIN64)
  825. memcpy(&efds,&_exceptfds,sizeof(efds));
  826. #else
  827. FD_ZERO(&efds);
  828. #endif
  829. tv.tv_sec = (long)(timeout / 1000);
  830. tv.tv_usec = (long)((timeout % 1000) * 1000);
  831. if (::select((int)_nfds + 1,&rfds,&wfds,&efds,(timeout > 0) ? &tv : (struct timeval *)0) <= 0)
  832. return;
  833. if (FD_ISSET(_whackReceiveSocket,&rfds)) {
  834. char tmp[16];
  835. #if defined(_WIN32) || defined(_WIN64)
  836. ::recv(_whackReceiveSocket,tmp,16,0);
  837. #else
  838. ::read(_whackReceiveSocket,tmp,16);
  839. #endif
  840. }
  841. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();) {
  842. switch (s->type) {
  843. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  844. #if defined(_WIN32) || defined(_WIN64)
  845. if (FD_ISSET(s->sock,&efds)) {
  846. this->close((PhySocket *)&(*s),true);
  847. } else // ... if
  848. #endif
  849. if (FD_ISSET(s->sock,&wfds)) {
  850. socklen_t slen = sizeof(ss);
  851. if (::getpeername(s->sock,(struct sockaddr *)&ss,&slen) != 0) {
  852. this->close((PhySocket *)&(*s),true);
  853. } else {
  854. s->type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  855. FD_SET(s->sock,&_readfds);
  856. FD_CLR(s->sock,&_writefds);
  857. #if defined(_WIN32) || defined(_WIN64)
  858. FD_CLR(s->sock,&_exceptfds);
  859. #endif
  860. try {
  861. _handler->phyOnTcpConnect((PhySocket *)&(*s),&(s->uptr),true);
  862. } catch ( ... ) {}
  863. }
  864. }
  865. break;
  866. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  867. case ZT_PHY_SOCKET_TCP_IN: {
  868. ZT_PHY_SOCKFD_TYPE sock = s->sock; // if closed, s->sock becomes invalid as s is no longer dereferencable
  869. if (FD_ISSET(sock,&rfds)) {
  870. long n = (long)::recv(sock,buf,sizeof(buf),0);
  871. if (n <= 0) {
  872. this->close((PhySocket *)&(*s),true);
  873. } else {
  874. try {
  875. _handler->phyOnTcpData((PhySocket *)&(*s),&(s->uptr),(void *)buf,(unsigned long)n);
  876. } catch ( ... ) {}
  877. }
  878. }
  879. if ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds))) {
  880. try {
  881. _handler->phyOnTcpWritable((PhySocket *)&(*s),&(s->uptr));
  882. } catch ( ... ) {}
  883. }
  884. } break;
  885. case ZT_PHY_SOCKET_TCP_LISTEN:
  886. if (FD_ISSET(s->sock,&rfds)) {
  887. memset(&ss,0,sizeof(ss));
  888. socklen_t slen = sizeof(ss);
  889. ZT_PHY_SOCKFD_TYPE newSock = ::accept(s->sock,(struct sockaddr *)&ss,&slen);
  890. if (ZT_PHY_SOCKFD_VALID(newSock)) {
  891. if (_socks.size() >= ZT_PHY_MAX_SOCKETS) {
  892. ZT_PHY_CLOSE_SOCKET(newSock);
  893. } else {
  894. #if defined(_WIN32) || defined(_WIN64)
  895. { BOOL f = (_noDelay ? TRUE : FALSE); setsockopt(newSock,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  896. { u_long iMode=1; ioctlsocket(newSock,FIONBIO,&iMode); }
  897. #else
  898. { int f = (_noDelay ? 1 : 0); setsockopt(newSock,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f)); }
  899. fcntl(newSock,F_SETFL,O_NONBLOCK);
  900. #endif
  901. _socks.push_back(PhySocketImpl());
  902. PhySocketImpl &sws = _socks.back();
  903. FD_SET(newSock,&_readfds);
  904. if ((long)newSock > _nfds)
  905. _nfds = (long)newSock;
  906. sws.type = ZT_PHY_SOCKET_TCP_IN;
  907. sws.sock = newSock;
  908. sws.uptr = (void *)0;
  909. memcpy(&(sws.saddr),&ss,sizeof(struct sockaddr_storage));
  910. try {
  911. _handler->phyOnTcpAccept((PhySocket *)&(*s),(PhySocket *)&(_socks.back()),&(s->uptr),&(sws.uptr),(const struct sockaddr *)&(sws.saddr));
  912. } catch ( ... ) {}
  913. }
  914. }
  915. }
  916. break;
  917. case ZT_PHY_SOCKET_UDP:
  918. if (FD_ISSET(s->sock,&rfds)) {
  919. for(int k=0;k<1024;++k) {
  920. memset(&ss,0,sizeof(ss));
  921. socklen_t slen = sizeof(ss);
  922. long n = (long)::recvfrom(s->sock,buf,sizeof(buf),0,(struct sockaddr *)&ss,&slen);
  923. if (n > 0) {
  924. try {
  925. _handler->phyOnDatagram((PhySocket *)&(*s),&(s->uptr),(const struct sockaddr *)&(s->saddr),(const struct sockaddr *)&ss,(void *)buf,(unsigned long)n);
  926. } catch ( ... ) {}
  927. } else if (n < 0)
  928. break;
  929. }
  930. }
  931. break;
  932. case ZT_PHY_SOCKET_UNIX_IN: {
  933. #ifdef __UNIX_LIKE__
  934. ZT_PHY_SOCKFD_TYPE sock = s->sock; // if closed, s->sock becomes invalid as s is no longer dereferencable
  935. if ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds))) {
  936. try {
  937. _handler->phyOnUnixWritable((PhySocket *)&(*s),&(s->uptr));
  938. } catch ( ... ) {}
  939. }
  940. if (FD_ISSET(sock,&rfds)) {
  941. long n = (long)::read(sock,buf,sizeof(buf));
  942. if (n <= 0) {
  943. this->close((PhySocket *)&(*s),true);
  944. } else {
  945. try {
  946. _handler->phyOnUnixData((PhySocket *)&(*s),&(s->uptr),(void *)buf,(unsigned long)n);
  947. } catch ( ... ) {}
  948. }
  949. }
  950. #endif // __UNIX_LIKE__
  951. } break;
  952. case ZT_PHY_SOCKET_UNIX_LISTEN:
  953. #ifdef __UNIX_LIKE__
  954. if (FD_ISSET(s->sock,&rfds)) {
  955. memset(&ss,0,sizeof(ss));
  956. socklen_t slen = sizeof(ss);
  957. ZT_PHY_SOCKFD_TYPE newSock = ::accept(s->sock,(struct sockaddr *)&ss,&slen);
  958. if (ZT_PHY_SOCKFD_VALID(newSock)) {
  959. if (_socks.size() >= ZT_PHY_MAX_SOCKETS) {
  960. ZT_PHY_CLOSE_SOCKET(newSock);
  961. } else {
  962. fcntl(newSock,F_SETFL,O_NONBLOCK);
  963. _socks.push_back(PhySocketImpl());
  964. PhySocketImpl &sws = _socks.back();
  965. FD_SET(newSock,&_readfds);
  966. if ((long)newSock > _nfds)
  967. _nfds = (long)newSock;
  968. sws.type = ZT_PHY_SOCKET_UNIX_IN;
  969. sws.sock = newSock;
  970. sws.uptr = (void *)0;
  971. memcpy(&(sws.saddr),&ss,sizeof(struct sockaddr_storage));
  972. try {
  973. //_handler->phyOnUnixAccept((PhySocket *)&(*s),(PhySocket *)&(_socks.back()),&(s->uptr),&(sws.uptr));
  974. } catch ( ... ) {}
  975. }
  976. }
  977. }
  978. #endif // __UNIX_LIKE__
  979. break;
  980. case ZT_PHY_SOCKET_FD: {
  981. ZT_PHY_SOCKFD_TYPE sock = s->sock;
  982. const bool readable = ((FD_ISSET(sock,&rfds))&&(FD_ISSET(sock,&_readfds)));
  983. const bool writable = ((FD_ISSET(sock,&wfds))&&(FD_ISSET(sock,&_writefds)));
  984. if ((readable)||(writable)) {
  985. try {
  986. //_handler->phyOnFileDescriptorActivity((PhySocket *)&(*s),&(s->uptr),readable,writable);
  987. } catch ( ... ) {}
  988. }
  989. } break;
  990. default:
  991. break;
  992. }
  993. if (s->type == ZT_PHY_SOCKET_CLOSED)
  994. _socks.erase(s++);
  995. else ++s;
  996. }
  997. }
  998. /**
  999. * @param sock Socket to close
  1000. * @param callHandlers If true, call handlers for TCP connect (success: false) or close (default: true)
  1001. */
  1002. inline void close(PhySocket *sock,bool callHandlers = true)
  1003. {
  1004. if (!sock)
  1005. return;
  1006. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  1007. if (sws.type == ZT_PHY_SOCKET_CLOSED)
  1008. return;
  1009. FD_CLR(sws.sock,&_readfds);
  1010. FD_CLR(sws.sock,&_writefds);
  1011. #if defined(_WIN32) || defined(_WIN64)
  1012. FD_CLR(sws.sock,&_exceptfds);
  1013. #endif
  1014. if (sws.type != ZT_PHY_SOCKET_FD)
  1015. ZT_PHY_CLOSE_SOCKET(sws.sock);
  1016. #ifdef __UNIX_LIKE__
  1017. if (sws.type == ZT_PHY_SOCKET_UNIX_LISTEN)
  1018. ::unlink(((struct sockaddr_un *)(&(sws.saddr)))->sun_path);
  1019. #endif // __UNIX_LIKE__
  1020. if (callHandlers) {
  1021. switch(sws.type) {
  1022. case ZT_PHY_SOCKET_TCP_OUT_PENDING:
  1023. try {
  1024. _handler->phyOnTcpConnect(sock,&(sws.uptr),false);
  1025. } catch ( ... ) {}
  1026. break;
  1027. case ZT_PHY_SOCKET_TCP_OUT_CONNECTED:
  1028. case ZT_PHY_SOCKET_TCP_IN:
  1029. try {
  1030. _handler->phyOnTcpClose(sock,&(sws.uptr));
  1031. } catch ( ... ) {}
  1032. break;
  1033. case ZT_PHY_SOCKET_UNIX_IN:
  1034. #ifdef __UNIX_LIKE__
  1035. try {
  1036. _handler->phyOnUnixClose(sock,&(sws.uptr));
  1037. } catch ( ... ) {}
  1038. #endif // __UNIX_LIKE__
  1039. break;
  1040. default:
  1041. break;
  1042. }
  1043. }
  1044. // Causes entry to be deleted from list in poll(), ignored elsewhere
  1045. sws.type = ZT_PHY_SOCKET_CLOSED;
  1046. if ((long)sws.sock >= (long)_nfds) {
  1047. long nfds = (long)_whackSendSocket;
  1048. if ((long)_whackReceiveSocket > nfds)
  1049. nfds = (long)_whackReceiveSocket;
  1050. for(typename std::list<PhySocketImpl>::iterator s(_socks.begin());s!=_socks.end();++s) {
  1051. if ((s->type != ZT_PHY_SOCKET_CLOSED)&&((long)s->sock > nfds))
  1052. nfds = (long)s->sock;
  1053. }
  1054. _nfds = nfds;
  1055. }
  1056. }
  1057. };
  1058. } // namespace ZeroTier
  1059. #endif