Phy.hpp 37 KB

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