Phy.hpp 35 KB

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