Phy.hpp 36 KB

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