Phy.hpp 34 KB

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