Phy.hpp 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2018 ZeroTier, Inc. https://www.zerotier.com/
  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. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #ifndef ZT_PHY_HPP
  27. #define ZT_PHY_HPP
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <list>
  32. #include <stdexcept>
  33. #if defined(_WIN32) || defined(_WIN64)
  34. #include <WinSock2.h>
  35. #include <WS2tcpip.h>
  36. #include <Windows.h>
  37. #define ZT_PHY_SOCKFD_TYPE SOCKET
  38. #define ZT_PHY_SOCKFD_NULL (INVALID_SOCKET)
  39. #define ZT_PHY_SOCKFD_VALID(s) ((s) != INVALID_SOCKET)
  40. #define ZT_PHY_CLOSE_SOCKET(s) ::closesocket(s)
  41. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  42. #define ZT_PHY_MAX_INTERCEPTS ZT_PHY_MAX_SOCKETS
  43. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  44. #else // not Windows
  45. #include <errno.h>
  46. #include <signal.h>
  47. #include <unistd.h>
  48. #include <fcntl.h>
  49. #include <sys/time.h>
  50. #include <sys/types.h>
  51. #include <sys/select.h>
  52. #include <sys/socket.h>
  53. #include <sys/un.h>
  54. #include <arpa/inet.h>
  55. #include <netinet/in.h>
  56. #include <netinet/tcp.h>
  57. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  58. #ifndef IPV6_DONTFRAG
  59. #define IPV6_DONTFRAG 62
  60. #endif
  61. #endif
  62. #define ZT_PHY_SOCKFD_TYPE int
  63. #define ZT_PHY_SOCKFD_NULL (-1)
  64. #define ZT_PHY_SOCKFD_VALID(s) ((s) > -1)
  65. #define ZT_PHY_CLOSE_SOCKET(s) ::close(s)
  66. #define ZT_PHY_MAX_SOCKETS (FD_SETSIZE)
  67. #define ZT_PHY_MAX_INTERCEPTS ZT_PHY_MAX_SOCKETS
  68. #define ZT_PHY_SOCKADDR_STORAGE_TYPE struct sockaddr_storage
  69. #endif // Windows or not
  70. namespace ZeroTier {
  71. /**
  72. * Opaque socket type
  73. */
  74. typedef void PhySocket;
  75. /**
  76. * Simple templated non-blocking sockets implementation
  77. *
  78. * Yes there is boost::asio and libuv, but I like small binaries and I hate
  79. * build dependencies. Both drag in a whole bunch of pasta with them.
  80. *
  81. * This class is templated on a pointer to a handler class which must
  82. * implement the following functions:
  83. *
  84. * For all platforms:
  85. *
  86. * phyOnDatagram(PhySocket *sock,void **uptr,const struct sockaddr *localAddr,const struct sockaddr *from,void *data,unsigned long len)
  87. * phyOnTcpConnect(PhySocket *sock,void **uptr,bool success)
  88. * phyOnTcpAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN,const struct sockaddr *from)
  89. * phyOnTcpClose(PhySocket *sock,void **uptr)
  90. * phyOnTcpData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  91. * phyOnTcpWritable(PhySocket *sock,void **uptr)
  92. * phyOnFileDescriptorActivity(PhySocket *sock,void **uptr,bool readable,bool writable)
  93. *
  94. * On Linux/OSX/Unix only (not required/used on Windows or elsewhere):
  95. *
  96. * phyOnUnixAccept(PhySocket *sockL,PhySocket *sockN,void **uptrL,void **uptrN)
  97. * phyOnUnixClose(PhySocket *sock,void **uptr)
  98. * phyOnUnixData(PhySocket *sock,void **uptr,void *data,unsigned long len)
  99. * phyOnUnixWritable(PhySocket *sock,void **uptr)
  100. *
  101. * These templates typically refer to function objects. Templates are used to
  102. * avoid the call overhead of indirection, which is surprisingly high for high
  103. * bandwidth applications pushing a lot of packets.
  104. *
  105. * The 'sock' pointer above is an opaque pointer to a socket. Each socket
  106. * has a 'uptr' user-settable/modifiable pointer associated with it, which
  107. * can be set on bind/connect calls and is passed as a void ** to permit
  108. * resetting at any time. The ACCEPT handler takes two sets of sock and
  109. * uptr: sockL and uptrL for the listen socket, and sockN and uptrN for
  110. * the new TCP connection socket that has just been created.
  111. *
  112. * Handlers are always called. On outgoing TCP connection, CONNECT is always
  113. * called on either success or failure followed by DATA and/or WRITABLE as
  114. * indicated. On socket close, handlers are called unless close() is told
  115. * explicitly not to call handlers. It is safe to close a socket within a
  116. * handler, and in that case close() can be told not to call handlers to
  117. * prevent recursion.
  118. *
  119. * This isn't thread-safe with the exception of whack(), which is safe to
  120. * call from another thread to abort poll().
  121. */
  122. template <typename HANDLER_PTR_TYPE>
  123. class Phy
  124. {
  125. private:
  126. HANDLER_PTR_TYPE _handler;
  127. enum PhySocketType
  128. {
  129. ZT_PHY_SOCKET_CLOSED = 0x00, // socket is closed, will be removed on next poll()
  130. ZT_PHY_SOCKET_TCP_OUT_PENDING = 0x01,
  131. ZT_PHY_SOCKET_TCP_OUT_CONNECTED = 0x02,
  132. ZT_PHY_SOCKET_TCP_IN = 0x03,
  133. ZT_PHY_SOCKET_TCP_LISTEN = 0x04,
  134. ZT_PHY_SOCKET_UDP = 0x05,
  135. ZT_PHY_SOCKET_FD = 0x06,
  136. ZT_PHY_SOCKET_UNIX_IN = 0x07,
  137. ZT_PHY_SOCKET_UNIX_LISTEN = 0x08
  138. };
  139. struct PhySocketImpl
  140. {
  141. PhySocketType type;
  142. ZT_PHY_SOCKFD_TYPE sock;
  143. void *uptr; // user-settable pointer
  144. ZT_PHY_SOCKADDR_STORAGE_TYPE saddr; // remote for TCP_OUT and TCP_IN, local for TCP_LISTEN, RAW, and UDP
  145. };
  146. std::list<PhySocketImpl> _socks;
  147. fd_set _readfds;
  148. fd_set _writefds;
  149. #if defined(_WIN32) || defined(_WIN64)
  150. fd_set _exceptfds;
  151. #endif
  152. long _nfds;
  153. ZT_PHY_SOCKFD_TYPE _whackReceiveSocket;
  154. ZT_PHY_SOCKFD_TYPE _whackSendSocket;
  155. bool _noDelay;
  156. bool _noCheck;
  157. public:
  158. /**
  159. * @param handler Pointer of type HANDLER_PTR_TYPE to handler
  160. * @param noDelay If true, disable TCP NAGLE algorithm on TCP sockets
  161. * @param noCheck If true, attempt to set UDP SO_NO_CHECK option to disable sending checksums
  162. */
  163. Phy(HANDLER_PTR_TYPE handler,bool noDelay,bool noCheck) :
  164. _handler(handler)
  165. {
  166. FD_ZERO(&_readfds);
  167. FD_ZERO(&_writefds);
  168. #if defined(_WIN32) || defined(_WIN64)
  169. FD_ZERO(&_exceptfds);
  170. SOCKET pipes[2];
  171. { // hack copied from StackOverflow, behaves a bit like pipe() on *nix systems
  172. struct sockaddr_in inaddr;
  173. struct sockaddr addr;
  174. SOCKET lst=::socket(AF_INET, SOCK_STREAM,IPPROTO_TCP);
  175. if (lst == INVALID_SOCKET)
  176. throw std::runtime_error("unable to create pipes for select() abort");
  177. memset(&inaddr, 0, sizeof(inaddr));
  178. memset(&addr, 0, sizeof(addr));
  179. inaddr.sin_family = AF_INET;
  180. inaddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  181. inaddr.sin_port = 0;
  182. int yes=1;
  183. setsockopt(lst,SOL_SOCKET,SO_REUSEADDR,(char*)&yes,sizeof(yes));
  184. bind(lst,(struct sockaddr *)&inaddr,sizeof(inaddr));
  185. listen(lst,1);
  186. int len=sizeof(inaddr);
  187. getsockname(lst, &addr,&len);
  188. pipes[0]=::socket(AF_INET, SOCK_STREAM,0);
  189. if (pipes[0] == INVALID_SOCKET)
  190. throw std::runtime_error("unable to create pipes for select() abort");
  191. connect(pipes[0],&addr,len);
  192. pipes[1]=accept(lst,0,0);
  193. closesocket(lst);
  194. }
  195. #else // not Windows
  196. int pipes[2];
  197. if (::pipe(pipes))
  198. throw std::runtime_error("unable to create pipes for select() abort");
  199. #endif // Windows or not
  200. _nfds = (pipes[0] > pipes[1]) ? (long)pipes[0] : (long)pipes[1];
  201. _whackReceiveSocket = pipes[0];
  202. _whackSendSocket = pipes[1];
  203. _noDelay = noDelay;
  204. _noCheck = noCheck;
  205. }
  206. ~Phy()
  207. {
  208. for(typename std::list<PhySocketImpl>::const_iterator s(_socks.begin());s!=_socks.end();++s) {
  209. if (s->type != ZT_PHY_SOCKET_CLOSED)
  210. this->close((PhySocket *)&(*s),true);
  211. }
  212. ZT_PHY_CLOSE_SOCKET(_whackReceiveSocket);
  213. ZT_PHY_CLOSE_SOCKET(_whackSendSocket);
  214. }
  215. /**
  216. * @param s Socket object
  217. * @return Underlying OS-type (usually int or long) file descriptor associated with object
  218. */
  219. static inline ZT_PHY_SOCKFD_TYPE getDescriptor(PhySocket *s) throw() { return reinterpret_cast<PhySocketImpl *>(s)->sock; }
  220. /**
  221. * @param s Socket object
  222. * @return Pointer to user object
  223. */
  224. static inline void** getuptr(PhySocket *s) throw() { return &(reinterpret_cast<PhySocketImpl *>(s)->uptr); }
  225. /**
  226. * Cause poll() to stop waiting immediately
  227. *
  228. * This can be used to reset the polling loop after changes that require
  229. * attention, or to shut down a background thread that is waiting, etc.
  230. */
  231. inline void whack()
  232. {
  233. #if defined(_WIN32) || defined(_WIN64)
  234. ::send(_whackSendSocket,(const char *)this,1,0);
  235. #else
  236. (void)(::write(_whackSendSocket,(PhySocket *)this,1));
  237. #endif
  238. }
  239. /**
  240. * @return Number of open sockets
  241. */
  242. inline unsigned long count() const throw() { return _socks.size(); }
  243. /**
  244. * @return Maximum number of sockets allowed
  245. */
  246. inline unsigned long maxCount() const throw() { return ZT_PHY_MAX_SOCKETS; }
  247. /**
  248. * Wrap a raw file descriptor in a PhySocket structure
  249. *
  250. * This can be used to select/poll on a raw file descriptor as part of this
  251. * class's I/O loop. By default the fd is set for read notification but
  252. * this can be controlled with setNotifyReadable(). When any detected
  253. * condition is present, the phyOnFileDescriptorActivity() callback is
  254. * called with one or both of its arguments 'true'.
  255. *
  256. * The Phy<>::close() method *must* be called when you're done with this
  257. * file descriptor to remove it from the select/poll set, but unlike other
  258. * types of sockets Phy<> does not actually close the underlying fd or
  259. * otherwise manage its life cycle. There is also no close notification
  260. * callback for this fd, since Phy<> doesn't actually perform reading or
  261. * writing or detect error conditions. This is only useful for adding a
  262. * file descriptor to Phy<> to select/poll on it.
  263. *
  264. * @param fd Raw file descriptor
  265. * @param uptr User pointer to supply to callbacks
  266. * @return PhySocket wrapping fd or NULL on failure (out of memory or too many sockets)
  267. */
  268. inline PhySocket *wrapSocket(ZT_PHY_SOCKFD_TYPE fd,void *uptr = (void *)0)
  269. {
  270. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  271. return (PhySocket *)0;
  272. try {
  273. _socks.push_back(PhySocketImpl());
  274. } catch ( ... ) {
  275. return (PhySocket *)0;
  276. }
  277. PhySocketImpl &sws = _socks.back();
  278. if ((long)fd > _nfds)
  279. _nfds = (long)fd;
  280. FD_SET(fd,&_readfds);
  281. sws.type = ZT_PHY_SOCKET_UNIX_IN; /* TODO: Type was changed to allow for CBs with new RPC model */
  282. sws.sock = fd;
  283. sws.uptr = uptr;
  284. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  285. // no sockaddr for this socket type, leave saddr null
  286. return (PhySocket *)&sws;
  287. }
  288. /**
  289. * Bind a UDP socket
  290. *
  291. * @param localAddress Local endpoint address and port
  292. * @param uptr Initial value of user pointer associated with this socket (default: NULL)
  293. * @param bufferSize Desired socket receive/send buffer size -- will set as close to this as possible (default: 0, leave alone)
  294. * @return Socket or NULL on failure to bind
  295. */
  296. inline PhySocket *udpBind(const struct sockaddr *localAddress,void *uptr = (void *)0,int bufferSize = 0)
  297. {
  298. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  299. return (PhySocket *)0;
  300. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_DGRAM,0);
  301. if (!ZT_PHY_SOCKFD_VALID(s))
  302. return (PhySocket *)0;
  303. if (bufferSize > 0) {
  304. int bs = bufferSize;
  305. while (bs >= 65536) {
  306. int tmpbs = bs;
  307. if (setsockopt(s,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  308. break;
  309. bs -= 16384;
  310. }
  311. bs = bufferSize;
  312. while (bs >= 65536) {
  313. int tmpbs = bs;
  314. if (setsockopt(s,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  315. break;
  316. bs -= 16384;
  317. }
  318. }
  319. #if defined(_WIN32) || defined(_WIN64)
  320. {
  321. BOOL f;
  322. if (localAddress->sa_family == AF_INET6) {
  323. f = TRUE; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  324. f = FALSE; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,(const char *)&f,sizeof(f));
  325. }
  326. f = FALSE; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  327. f = TRUE; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(const char *)&f,sizeof(f));
  328. }
  329. #else // not Windows
  330. {
  331. int f;
  332. if (localAddress->sa_family == AF_INET6) {
  333. f = 1; setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  334. #ifdef IPV6_MTU_DISCOVER
  335. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_MTU_DISCOVER,&f,sizeof(f));
  336. #endif
  337. #ifdef IPV6_DONTFRAG
  338. f = 0; setsockopt(s,IPPROTO_IPV6,IPV6_DONTFRAG,&f,sizeof(f));
  339. #endif
  340. }
  341. f = 0; setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  342. f = 1; setsockopt(s,SOL_SOCKET,SO_BROADCAST,(void *)&f,sizeof(f));
  343. #ifdef IP_DONTFRAG
  344. f = 0; setsockopt(s,IPPROTO_IP,IP_DONTFRAG,&f,sizeof(f));
  345. #endif
  346. #ifdef IP_MTU_DISCOVER
  347. f = 0; setsockopt(s,IPPROTO_IP,IP_MTU_DISCOVER,&f,sizeof(f));
  348. #endif
  349. #ifdef SO_NO_CHECK
  350. // For now at least we only set SO_NO_CHECK on IPv4 sockets since some
  351. // IPv6 stacks incorrectly discard zero checksum packets. May remove
  352. // this restriction later once broken stuff dies more.
  353. if ((localAddress->sa_family == AF_INET)&&(_noCheck)) {
  354. f = 1; setsockopt(s,SOL_SOCKET,SO_NO_CHECK,(void *)&f,sizeof(f));
  355. }
  356. #endif
  357. }
  358. #endif // Windows or not
  359. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  360. ZT_PHY_CLOSE_SOCKET(s);
  361. return (PhySocket *)0;
  362. }
  363. #if defined(_WIN32) || defined(_WIN64)
  364. { u_long iMode=1; ioctlsocket(s,FIONBIO,&iMode); }
  365. #else
  366. fcntl(s,F_SETFL,O_NONBLOCK);
  367. #endif
  368. try {
  369. _socks.push_back(PhySocketImpl());
  370. } catch ( ... ) {
  371. ZT_PHY_CLOSE_SOCKET(s);
  372. return (PhySocket *)0;
  373. }
  374. PhySocketImpl &sws = _socks.back();
  375. if ((long)s > _nfds)
  376. _nfds = (long)s;
  377. FD_SET(s,&_readfds);
  378. sws.type = ZT_PHY_SOCKET_UDP;
  379. sws.sock = s;
  380. sws.uptr = uptr;
  381. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  382. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  383. return (PhySocket *)&sws;
  384. }
  385. /**
  386. * Set the IP TTL for the next outgoing packet (for IPv4 UDP sockets only)
  387. *
  388. * @param ttl New TTL (0 or >255 will set it to 255)
  389. * @return True on success
  390. */
  391. inline bool setIp4UdpTtl(PhySocket *sock,unsigned int ttl)
  392. {
  393. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  394. #if defined(_WIN32) || defined(_WIN64)
  395. DWORD tmp = ((ttl == 0)||(ttl > 255)) ? 255 : (DWORD)ttl;
  396. return (::setsockopt(sws.sock,IPPROTO_IP,IP_TTL,(const char *)&tmp,sizeof(tmp)) == 0);
  397. #else
  398. int tmp = ((ttl == 0)||(ttl > 255)) ? 255 : (int)ttl;
  399. return (::setsockopt(sws.sock,IPPROTO_IP,IP_TTL,(void *)&tmp,sizeof(tmp)) == 0);
  400. #endif
  401. }
  402. /**
  403. * Send a UDP packet
  404. *
  405. * @param sock UDP socket
  406. * @param remoteAddress Destination address (must be correct type for socket)
  407. * @param data Data to send
  408. * @param len Length of packet
  409. * @return True if packet appears to have been sent successfully
  410. */
  411. inline bool udpSend(PhySocket *sock,const struct sockaddr *remoteAddress,const void *data,unsigned long len)
  412. {
  413. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  414. #if defined(_WIN32) || defined(_WIN64)
  415. 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);
  416. #else
  417. return ((long)::sendto(sws.sock,data,len,0,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in)) == (long)len);
  418. #endif
  419. }
  420. #ifdef __UNIX_LIKE__
  421. /**
  422. * Listen for connections on a Unix domain socket
  423. *
  424. * @param path Path to Unix domain socket
  425. * @param uptr Arbitrary pointer to associate
  426. * @return PhySocket or NULL if cannot bind
  427. */
  428. inline PhySocket *unixListen(const char *path,void *uptr = (void *)0)
  429. {
  430. struct sockaddr_un sun;
  431. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  432. return (PhySocket *)0;
  433. memset(&sun,0,sizeof(sun));
  434. sun.sun_family = AF_UNIX;
  435. if (strlen(path) >= sizeof(sun.sun_path))
  436. return (PhySocket *)0;
  437. strcpy(sun.sun_path,path);
  438. ZT_PHY_SOCKFD_TYPE s = ::socket(PF_UNIX,SOCK_STREAM,0);
  439. if (!ZT_PHY_SOCKFD_VALID(s))
  440. return (PhySocket *)0;
  441. ::fcntl(s,F_SETFL,O_NONBLOCK);
  442. ::unlink(path);
  443. if (::bind(s,(struct sockaddr *)&sun,sizeof(struct sockaddr_un)) != 0) {
  444. ZT_PHY_CLOSE_SOCKET(s);
  445. return (PhySocket *)0;
  446. }
  447. if (::listen(s,128) != 0) {
  448. ZT_PHY_CLOSE_SOCKET(s);
  449. return (PhySocket *)0;
  450. }
  451. try {
  452. _socks.push_back(PhySocketImpl());
  453. } catch ( ... ) {
  454. ZT_PHY_CLOSE_SOCKET(s);
  455. return (PhySocket *)0;
  456. }
  457. PhySocketImpl &sws = _socks.back();
  458. if ((long)s > _nfds)
  459. _nfds = (long)s;
  460. FD_SET(s,&_readfds);
  461. sws.type = ZT_PHY_SOCKET_UNIX_LISTEN;
  462. sws.sock = s;
  463. sws.uptr = uptr;
  464. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  465. memcpy(&(sws.saddr),&sun,sizeof(struct sockaddr_un));
  466. return (PhySocket *)&sws;
  467. }
  468. #endif // __UNIX_LIKE__
  469. /**
  470. * Bind a local listen socket to listen for new TCP connections
  471. *
  472. * @param localAddress Local address and port
  473. * @param uptr Initial value of uptr for new socket (default: NULL)
  474. * @return Socket or NULL on failure to bind
  475. */
  476. inline PhySocket *tcpListen(const struct sockaddr *localAddress,void *uptr = (void *)0)
  477. {
  478. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  479. return (PhySocket *)0;
  480. ZT_PHY_SOCKFD_TYPE s = ::socket(localAddress->sa_family,SOCK_STREAM,0);
  481. if (!ZT_PHY_SOCKFD_VALID(s))
  482. return (PhySocket *)0;
  483. #if defined(_WIN32) || defined(_WIN64)
  484. {
  485. BOOL f;
  486. f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f));
  487. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  488. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  489. u_long iMode=1;
  490. ioctlsocket(s,FIONBIO,&iMode);
  491. }
  492. #else
  493. {
  494. int f;
  495. f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f));
  496. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  497. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  498. fcntl(s,F_SETFL,O_NONBLOCK);
  499. }
  500. #endif
  501. if (::bind(s,localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  502. ZT_PHY_CLOSE_SOCKET(s);
  503. return (PhySocket *)0;
  504. }
  505. if (::listen(s,1024)) {
  506. ZT_PHY_CLOSE_SOCKET(s);
  507. return (PhySocket *)0;
  508. }
  509. try {
  510. _socks.push_back(PhySocketImpl());
  511. } catch ( ... ) {
  512. ZT_PHY_CLOSE_SOCKET(s);
  513. return (PhySocket *)0;
  514. }
  515. PhySocketImpl &sws = _socks.back();
  516. if ((long)s > _nfds)
  517. _nfds = (long)s;
  518. FD_SET(s,&_readfds);
  519. sws.type = ZT_PHY_SOCKET_TCP_LISTEN;
  520. sws.sock = s;
  521. sws.uptr = uptr;
  522. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  523. memcpy(&(sws.saddr),localAddress,(localAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  524. return (PhySocket *)&sws;
  525. }
  526. /**
  527. * Start a non-blocking connect; CONNECT handler is called on success or failure
  528. *
  529. * A return value of NULL indicates a synchronous failure such as a
  530. * failure to open a socket. The TCP connection handler is not called
  531. * in this case.
  532. *
  533. * It is possible on some platforms for an "instant connect" to occur,
  534. * such as when connecting to a loopback address. In this case, the
  535. * 'connected' result parameter will be set to 'true' and if the
  536. * 'callConnectHandler' flag is true (the default) the TCP connect
  537. * handler will be called before the function returns.
  538. *
  539. * These semantics can be a bit confusing, but they're less so than
  540. * the underlying semantics of asynchronous TCP connect.
  541. *
  542. * @param remoteAddress Remote address
  543. * @param connected Result parameter: set to whether an "instant connect" has occurred (true if yes)
  544. * @param uptr Initial value of uptr for new socket (default: NULL)
  545. * @param callConnectHandler If true, call TCP connect handler even if result is known before function exit (default: true)
  546. * @return New socket or NULL on failure
  547. */
  548. inline PhySocket *tcpConnect(const struct sockaddr *remoteAddress,bool &connected,void *uptr = (void *)0,bool callConnectHandler = true)
  549. {
  550. if (_socks.size() >= ZT_PHY_MAX_SOCKETS)
  551. return (PhySocket *)0;
  552. ZT_PHY_SOCKFD_TYPE s = ::socket(remoteAddress->sa_family,SOCK_STREAM,0);
  553. if (!ZT_PHY_SOCKFD_VALID(s)) {
  554. connected = false;
  555. return (PhySocket *)0;
  556. }
  557. #if defined(_WIN32) || defined(_WIN64)
  558. {
  559. BOOL f;
  560. if (remoteAddress->sa_family == AF_INET6) { f = TRUE; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(const char *)&f,sizeof(f)); }
  561. f = TRUE; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(const char *)&f,sizeof(f));
  562. f = (_noDelay ? TRUE : FALSE); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  563. u_long iMode=1;
  564. ioctlsocket(s,FIONBIO,&iMode);
  565. }
  566. #else
  567. {
  568. int f;
  569. if (remoteAddress->sa_family == AF_INET6) { f = 1; ::setsockopt(s,IPPROTO_IPV6,IPV6_V6ONLY,(void *)&f,sizeof(f)); }
  570. f = 1; ::setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(void *)&f,sizeof(f));
  571. f = (_noDelay ? 1 : 0); setsockopt(s,IPPROTO_TCP,TCP_NODELAY,(char *)&f,sizeof(f));
  572. fcntl(s,F_SETFL,O_NONBLOCK);
  573. }
  574. #endif
  575. connected = true;
  576. if (::connect(s,remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in))) {
  577. connected = false;
  578. #if defined(_WIN32) || defined(_WIN64)
  579. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  580. #else
  581. if (errno != EINPROGRESS) {
  582. #endif
  583. ZT_PHY_CLOSE_SOCKET(s);
  584. return (PhySocket *)0;
  585. } // else connection is proceeding asynchronously...
  586. }
  587. try {
  588. _socks.push_back(PhySocketImpl());
  589. } catch ( ... ) {
  590. ZT_PHY_CLOSE_SOCKET(s);
  591. return (PhySocket *)0;
  592. }
  593. PhySocketImpl &sws = _socks.back();
  594. if ((long)s > _nfds)
  595. _nfds = (long)s;
  596. if (connected) {
  597. FD_SET(s,&_readfds);
  598. sws.type = ZT_PHY_SOCKET_TCP_OUT_CONNECTED;
  599. } else {
  600. FD_SET(s,&_writefds);
  601. #if defined(_WIN32) || defined(_WIN64)
  602. FD_SET(s,&_exceptfds);
  603. #endif
  604. sws.type = ZT_PHY_SOCKET_TCP_OUT_PENDING;
  605. }
  606. sws.sock = s;
  607. sws.uptr = uptr;
  608. memset(&(sws.saddr),0,sizeof(struct sockaddr_storage));
  609. memcpy(&(sws.saddr),remoteAddress,(remoteAddress->sa_family == AF_INET6) ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in));
  610. if ((callConnectHandler)&&(connected)) {
  611. try {
  612. _handler->phyOnTcpConnect((PhySocket *)&sws,&(sws.uptr),true);
  613. } catch ( ... ) {}
  614. }
  615. return (PhySocket *)&sws;
  616. }
  617. /**
  618. * Try to set buffer sizes as close to the given value as possible
  619. *
  620. * This will try the specified value and then lower values in 16K increments
  621. * until one works.
  622. *
  623. * @param sock Socket
  624. * @param receiveBufferSize Desired size of receive buffer
  625. * @param sendBufferSize Desired size of send buffer
  626. */
  627. inline void setBufferSizes(const PhySocket *sock,int receiveBufferSize,int sendBufferSize)
  628. {
  629. PhySocketImpl &sws = *(reinterpret_cast<PhySocketImpl *>(sock));
  630. if (receiveBufferSize > 0) {
  631. while (receiveBufferSize > 0) {
  632. int tmpbs = receiveBufferSize;
  633. if (::setsockopt(sws.sock,SOL_SOCKET,SO_RCVBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  634. break;
  635. receiveBufferSize -= 16384;
  636. }
  637. }
  638. if (sendBufferSize > 0) {
  639. while (sendBufferSize > 0) {
  640. int tmpbs = sendBufferSize;
  641. if (::setsockopt(sws.sock,SOL_SOCKET,SO_SNDBUF,(const char *)&tmpbs,sizeof(tmpbs)) == 0)
  642. break;
  643. sendBufferSize -= 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 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 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(int k=0;k<1024;++k) {
  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 *)&(s->saddr),(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,&wfds))&&(FD_ISSET(sock,&_writefds))) {
  906. try {
  907. _handler->phyOnUnixWritable((PhySocket *)&(*s),&(s->uptr),false);
  908. } catch ( ... ) {}
  909. }
  910. if (FD_ISSET(sock,&rfds)) {
  911. long n = (long)::read(sock,buf,sizeof(buf));
  912. if (n <= 0) {
  913. this->close((PhySocket *)&(*s),true);
  914. } else {
  915. try {
  916. _handler->phyOnUnixData((PhySocket *)&(*s),&(s->uptr),(void *)buf,(unsigned long)n);
  917. } catch ( ... ) {}
  918. }
  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