Phy.hpp 37 KB

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