Binder.hpp 9.8 KB

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