Phy.hpp 35 KB

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