Phy.hpp 36 KB

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