Binder.hpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_BINDER_HPP
  19. #define ZT_BINDER_HPP
  20. #include "../node/Constants.hpp"
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #ifdef __WINDOWS__
  26. #include <WinSock2.h>
  27. #include <Windows.h>
  28. #include <ShlObj.h>
  29. #include <netioapi.h>
  30. #include <iphlpapi.h>
  31. #else
  32. #include <sys/types.h>
  33. #include <sys/socket.h>
  34. #include <sys/wait.h>
  35. #include <unistd.h>
  36. #include <ifaddrs.h>
  37. #ifdef __LINUX__
  38. #include <sys/ioctl.h>
  39. #include <net/if.h>
  40. #endif
  41. #endif
  42. #include <string>
  43. #include <vector>
  44. #include <algorithm>
  45. #include <utility>
  46. #include <map>
  47. #include "../node/NonCopyable.hpp"
  48. #include "../node/InetAddress.hpp"
  49. #include "../node/Mutex.hpp"
  50. #include "Phy.hpp"
  51. /**
  52. * Period between binder rescans/refreshes
  53. *
  54. * OneService also does this on detected restarts.
  55. */
  56. #define ZT_BINDER_REFRESH_PERIOD 30000
  57. namespace ZeroTier {
  58. /**
  59. * Enumerates local devices and binds to all potential ZeroTier path endpoints
  60. *
  61. * This replaces binding to wildcard (0.0.0.0 and ::0) with explicit binding
  62. * as part of the path to default gateway support. Under the hood it uses
  63. * different queries on different OSes to enumerate devices, and also exposes
  64. * device enumeration and endpoint IP data for use elsewhere.
  65. *
  66. * On OSes that do not support local port enumeration or where this is not
  67. * meaningful, this degrades to binding to wildcard.
  68. */
  69. class Binder : NonCopyable
  70. {
  71. private:
  72. struct _Binding
  73. {
  74. _Binding() :
  75. udpSock((PhySocket *)0),
  76. tcpListenSock((PhySocket *)0),
  77. address() {}
  78. PhySocket *udpSock;
  79. PhySocket *tcpListenSock;
  80. InetAddress address;
  81. };
  82. public:
  83. Binder() {}
  84. /**
  85. * Close all bound ports
  86. *
  87. * This should be called on shutdown. It closes listen sockets and UDP ports
  88. * but not TCP connections from any TCP listen sockets.
  89. *
  90. * @param phy Physical interface
  91. */
  92. template<typename PHY_HANDLER_TYPE>
  93. void closeAll(Phy<PHY_HANDLER_TYPE> &phy)
  94. {
  95. Mutex::Lock _l(_lock);
  96. for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
  97. phy.close(i->udpSock,false);
  98. phy.close(i->tcpListenSock,false);
  99. }
  100. }
  101. /**
  102. * Scan local devices and addresses and rebind TCP and UDP
  103. *
  104. * This should be called after wake from sleep, on detected network device
  105. * changes, on startup, or periodically (e.g. every 30-60s).
  106. *
  107. * @param phy Physical interface
  108. * @param port Port to bind to on all interfaces (TCP and UDP)
  109. * @param ignoreInterfacesByName Ignore these interfaces by name
  110. * @param ignoreInterfacesByNamePrefix Ignore these interfaces by name-prefix (starts-with, e.g. zt ignores zt*)
  111. * @param ignoreInterfacesByAddress Ignore these interfaces by address
  112. * @tparam PHY_HANDLER_TYPE Type for Phy<> template
  113. * @tparam INTERFACE_CHECKER Type for class containing shouldBindInterface() method
  114. */
  115. template<typename PHY_HANDLER_TYPE,typename INTERFACE_CHECKER>
  116. void refresh(Phy<PHY_HANDLER_TYPE> &phy,unsigned int port,INTERFACE_CHECKER &ifChecker)
  117. {
  118. std::map<InetAddress,std::string> localIfAddrs;
  119. PhySocket *udps;
  120. //PhySocket *tcps;
  121. Mutex::Lock _l(_lock);
  122. #ifdef __WINDOWS__
  123. char aabuf[32768];
  124. ULONG aalen = sizeof(aabuf);
  125. if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
  126. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  127. while (a) {
  128. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  129. while (ua) {
  130. InetAddress ip(ua->Address.lpSockaddr);
  131. if (ifChecker.shouldBindInterface("",ip)) {
  132. switch(ip.ipScope()) {
  133. default: break;
  134. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  135. case InetAddress::IP_SCOPE_GLOBAL:
  136. case InetAddress::IP_SCOPE_SHARED:
  137. case InetAddress::IP_SCOPE_PRIVATE:
  138. ip.setPort(port);
  139. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string()));
  140. break;
  141. }
  142. }
  143. ua = ua->Next;
  144. }
  145. a = a->Next;
  146. }
  147. }
  148. #else // not __WINDOWS__
  149. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  150. struct ifaddrs *ifa;
  151. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  152. ifa = ifatbl;
  153. while (ifa) {
  154. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  155. InetAddress ip = *(ifa->ifa_addr);
  156. if (ifChecker.shouldBindInterface(ifa->ifa_name,ip)) {
  157. switch(ip.ipScope()) {
  158. default: break;
  159. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  160. case InetAddress::IP_SCOPE_GLOBAL:
  161. case InetAddress::IP_SCOPE_SHARED:
  162. case InetAddress::IP_SCOPE_PRIVATE:
  163. ip.setPort(port);
  164. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(ifa->ifa_name)));
  165. break;
  166. }
  167. }
  168. }
  169. ifa = ifa->ifa_next;
  170. }
  171. freeifaddrs(ifatbl);
  172. }
  173. #endif
  174. // Default to binding to wildcard if we can't enumerate addresses
  175. if (localIfAddrs.empty()) {
  176. localIfAddrs.insert(std::pair<InetAddress,std::string>(InetAddress((uint32_t)0,port),std::string()));
  177. localIfAddrs.insert(std::pair<InetAddress,std::string>(InetAddress((const void *)"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",16,port),std::string()));
  178. }
  179. // Close any old bindings to anything that doesn't exist anymore
  180. for(typename std::vector<_Binding>::const_iterator bi(_bindings.begin());bi!=_bindings.end();++bi) {
  181. if (localIfAddrs.find(bi->address) == localIfAddrs.end()) {
  182. phy.close(bi->udpSock,false);
  183. phy.close(bi->tcpListenSock,false);
  184. }
  185. }
  186. std::vector<_Binding> newBindings;
  187. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  188. typename std::vector<_Binding>::const_iterator bi(_bindings.begin());
  189. while (bi != _bindings.end()) {
  190. if (bi->address == ii->first) {
  191. newBindings.push_back(*bi);
  192. break;
  193. }
  194. ++bi;
  195. }
  196. if (bi == _bindings.end()) {
  197. udps = phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0,ZT_UDP_DESIRED_BUF_SIZE);
  198. if (udps) {
  199. //tcps = phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&ii),(void *)0);
  200. //if (tcps) {
  201. #ifdef __LINUX__
  202. // Bind Linux sockets to their device so routes tha we manage do not override physical routes (wish all platforms had this!)
  203. if (ii->second.length() > 0) {
  204. int fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(udps);
  205. char tmp[256];
  206. Utils::scopy(tmp,sizeof(tmp),ii->second.c_str());
  207. if (fd >= 0) {
  208. if (setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp)) != 0) {
  209. fprintf(stderr,"WARNING: unable to set SO_BINDTODEVICE to bind %s to %s\n",ii->first.toIpString().c_str(),ii->second.c_str());
  210. }
  211. }
  212. }
  213. #endif // __LINUX__
  214. newBindings.push_back(_Binding());
  215. newBindings.back().udpSock = udps;
  216. //newBindings.back().tcpListenSock = tcps;
  217. newBindings.back().address = ii->first;
  218. //} else {
  219. // phy.close(udps,false);
  220. //}
  221. }
  222. }
  223. }
  224. // Swapping pointers and then letting the old one fall out of scope is faster than copying again
  225. _bindings.swap(newBindings);
  226. }
  227. /**
  228. * Send a UDP packet from the specified local interface, or all
  229. *
  230. * Unfortunately even by examining the routing table there is no ultimately
  231. * robust way to tell where we might reach another host that works in all
  232. * environments. As a result, we send packets with null (wildcard) local
  233. * addresses from *every* bound interface.
  234. *
  235. * These are typically initial HELLOs, path probes, etc., since normal
  236. * conversations will have a local endpoint address. So the cost is low and
  237. * if the peer is not reachable via that route then the packet will go
  238. * nowhere and nothing will happen.
  239. *
  240. * It will of course only send via interface bindings of the same socket
  241. * family. No point in sending V4 via V6 or vice versa.
  242. *
  243. * In any case on most hosts there's only one or two interfaces that we
  244. * will use, so none of this is particularly costly.
  245. *
  246. * @param local Local interface address or null address for 'all'
  247. * @param remote Remote address
  248. * @param data Data to send
  249. * @param len Length of data
  250. * @param v4ttl If non-zero, send this packet with the specified IP TTL (IPv4 only)
  251. */
  252. template<typename PHY_HANDLER_TYPE>
  253. inline bool udpSend(Phy<PHY_HANDLER_TYPE> &phy,const InetAddress &local,const InetAddress &remote,const void *data,unsigned int len,unsigned int v4ttl = 0) const
  254. {
  255. Mutex::Lock _l(_lock);
  256. if (local) {
  257. for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
  258. if (i->address == local) {
  259. if ((v4ttl)&&(local.ss_family == AF_INET))
  260. phy.setIp4UdpTtl(i->udpSock,v4ttl);
  261. const bool result = phy.udpSend(i->udpSock,reinterpret_cast<const struct sockaddr *>(&remote),data,len);
  262. if ((v4ttl)&&(local.ss_family == AF_INET))
  263. phy.setIp4UdpTtl(i->udpSock,255);
  264. return result;
  265. }
  266. }
  267. return false;
  268. } else {
  269. bool result = false;
  270. for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
  271. if (i->address.ss_family == remote.ss_family) {
  272. if ((v4ttl)&&(remote.ss_family == AF_INET))
  273. phy.setIp4UdpTtl(i->udpSock,v4ttl);
  274. result |= phy.udpSend(i->udpSock,reinterpret_cast<const struct sockaddr *>(&remote),data,len);
  275. if ((v4ttl)&&(remote.ss_family == AF_INET))
  276. phy.setIp4UdpTtl(i->udpSock,255);
  277. }
  278. }
  279. return result;
  280. }
  281. }
  282. /**
  283. * @return All currently bound local interface addresses
  284. */
  285. inline std::vector<InetAddress> allBoundLocalInterfaceAddresses()
  286. {
  287. Mutex::Lock _l(_lock);
  288. std::vector<InetAddress> aa;
  289. for(std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i)
  290. aa.push_back(i->address);
  291. return aa;
  292. }
  293. private:
  294. std::vector<_Binding> _bindings;
  295. Mutex _lock;
  296. };
  297. } // namespace ZeroTier
  298. #endif