Binder.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2017 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_BINDER_HPP
  27. #define ZT_BINDER_HPP
  28. #include "../node/Constants.hpp"
  29. #include <stdint.h>
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <string.h>
  33. #ifdef __WINDOWS__
  34. #include <WinSock2.h>
  35. #include <Windows.h>
  36. #include <ShlObj.h>
  37. #include <netioapi.h>
  38. #include <iphlpapi.h>
  39. #else
  40. #include <sys/types.h>
  41. #include <sys/socket.h>
  42. #include <sys/wait.h>
  43. #include <unistd.h>
  44. #include <ifaddrs.h>
  45. #ifdef __LINUX__
  46. #include <sys/ioctl.h>
  47. #include <net/if.h>
  48. #endif
  49. #endif
  50. #include <string>
  51. #include <vector>
  52. #include <algorithm>
  53. #include <utility>
  54. #include <map>
  55. #include <set>
  56. #include "../node/NonCopyable.hpp"
  57. #include "../node/InetAddress.hpp"
  58. #include "../node/Mutex.hpp"
  59. #include "../node/Utils.hpp"
  60. #include "Phy.hpp"
  61. #include "OSUtils.hpp"
  62. // Period between refreshes of bindings
  63. #define ZT_BINDER_REFRESH_PERIOD 30000
  64. namespace ZeroTier {
  65. /**
  66. * Enumerates local devices and binds to all potential ZeroTier path endpoints
  67. *
  68. * This replaces binding to wildcard (0.0.0.0 and ::0) with explicit binding
  69. * as part of the path to default gateway support. Under the hood it uses
  70. * different queries on different OSes to enumerate devices, and also exposes
  71. * device enumeration and endpoint IP data for use elsewhere.
  72. *
  73. * On OSes that do not support local port enumeration or where this is not
  74. * meaningful, this degrades to binding to wildcard.
  75. */
  76. class Binder : NonCopyable
  77. {
  78. private:
  79. struct _Binding
  80. {
  81. _Binding() : udpSock((PhySocket *)0),tcpListenSock((PhySocket *)0) {}
  82. PhySocket *udpSock;
  83. PhySocket *tcpListenSock;
  84. InetAddress address;
  85. };
  86. public:
  87. Binder() {}
  88. /**
  89. * Close all bound ports, should be called on shutdown
  90. *
  91. * @param phy Physical interface
  92. */
  93. template<typename PHY_HANDLER_TYPE>
  94. void closeAll(Phy<PHY_HANDLER_TYPE> &phy)
  95. {
  96. Mutex::Lock _l(_lock);
  97. for(std::vector<_Binding>::iterator b(_bindings.begin());b!=_bindings.end();++b) {
  98. phy.close(b->udpSock,false);
  99. phy.close(b->tcpListenSock,false);
  100. }
  101. }
  102. /**
  103. * Scan local devices and addresses and rebind TCP and UDP
  104. *
  105. * This should be called after wake from sleep, on detected network device
  106. * changes, on startup, or periodically (e.g. every 30-60s).
  107. *
  108. * @param phy Physical interface
  109. * @param ports Ports to bind on all interfaces
  110. * @param ignoreInterfacesByName Ignore these interfaces by name
  111. * @param ignoreInterfacesByNamePrefix Ignore these interfaces by name-prefix (starts-with, e.g. zt ignores zt*)
  112. * @param ignoreInterfacesByAddress Ignore these interfaces by address
  113. * @tparam PHY_HANDLER_TYPE Type for Phy<> template
  114. * @tparam INTERFACE_CHECKER Type for class containing shouldBindInterface() method
  115. */
  116. template<typename PHY_HANDLER_TYPE,typename INTERFACE_CHECKER>
  117. void refresh(Phy<PHY_HANDLER_TYPE> &phy,unsigned int *ports,unsigned int portCount,INTERFACE_CHECKER &ifChecker)
  118. {
  119. std::map<InetAddress,std::string> localIfAddrs;
  120. PhySocket *udps,*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. for(int x=0;x<(int)portCount;++x) {
  139. ip.setPort(ports[x]);
  140. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string()));
  141. }
  142. break;
  143. }
  144. }
  145. ua = ua->Next;
  146. }
  147. a = a->Next;
  148. }
  149. }
  150. #else // not __WINDOWS__
  151. /* On Linux we use an alternative method if available since getifaddrs()
  152. * gets very slow when there are lots of network namespaces. This won't
  153. * work unless /proc/PID/net/if_inet6 exists and it may not on some
  154. * embedded systems, so revert to getifaddrs() there. */
  155. #ifdef __LINUX__
  156. char fn[256],tmp[256];
  157. std::set<std::string> ifnames;
  158. const unsigned long pid = (unsigned long)getpid();
  159. // Get all device names
  160. OSUtils::ztsnprintf(fn,sizeof(fn),"/proc/%lu/net/dev",pid);
  161. FILE *procf = fopen(fn,"r");
  162. if (procf) {
  163. while (fgets(tmp,sizeof(tmp),procf)) {
  164. tmp[255] = 0;
  165. char *saveptr = (char *)0;
  166. for(char *f=Utils::stok(tmp," \t\r\n:|",&saveptr);(f);f=Utils::stok((char *)0," \t\r\n:|",&saveptr)) {
  167. if ((strcmp(f,"Inter-") != 0)&&(strcmp(f,"face") != 0)&&(f[0] != 0))
  168. ifnames.insert(f);
  169. break; // we only want the first field
  170. }
  171. }
  172. fclose(procf);
  173. }
  174. // Get IPv6 addresses (and any device names we don't already know)
  175. OSUtils::ztsnprintf(fn,sizeof(fn),"/proc/%lu/net/if_inet6",pid);
  176. procf = fopen(fn,"r");
  177. if (procf) {
  178. while (fgets(tmp,sizeof(tmp),procf)) {
  179. tmp[255] = 0;
  180. char *saveptr = (char *)0;
  181. unsigned char ipbits[16];
  182. memset(ipbits,0,sizeof(ipbits));
  183. char *devname = (char *)0;
  184. int n = 0;
  185. for(char *f=Utils::stok(tmp," \t\r\n",&saveptr);(f);f=Utils::stok((char *)0," \t\r\n",&saveptr)) {
  186. switch(n++) {
  187. case 0: // IP in hex
  188. Utils::unhex(f,32,ipbits,16);
  189. break;
  190. case 5: // device name
  191. devname = f;
  192. break;
  193. }
  194. }
  195. if (devname) {
  196. ifnames.insert(devname);
  197. InetAddress ip(ipbits,16,0);
  198. if (ifChecker.shouldBindInterface(devname,ip)) {
  199. switch(ip.ipScope()) {
  200. default: break;
  201. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  202. case InetAddress::IP_SCOPE_GLOBAL:
  203. case InetAddress::IP_SCOPE_SHARED:
  204. case InetAddress::IP_SCOPE_PRIVATE:
  205. for(int x=0;x<portCount;++x) {
  206. ip.setPort(ports[x]);
  207. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(devname)));
  208. }
  209. break;
  210. }
  211. }
  212. }
  213. }
  214. fclose(procf);
  215. }
  216. // Get IPv4 addresses for each device
  217. if (ifnames.size() > 0) {
  218. const int controlfd = (int)socket(AF_INET,SOCK_DGRAM,0);
  219. struct ifconf configuration;
  220. configuration.ifc_len = 0;
  221. configuration.ifc_buf = nullptr;
  222. if (controlfd < 0) goto ip4_address_error;
  223. if (ioctl(controlfd, SIOCGIFCONF, &configuration) < 0) goto ip4_address_error;
  224. configuration.ifc_buf = (char*)malloc(configuration.ifc_len);
  225. if (ioctl(controlfd, SIOCGIFCONF, &configuration) < 0) goto ip4_address_error;
  226. for (int i=0; i < (int)(configuration.ifc_len / sizeof(ifreq)); i ++) {
  227. struct ifreq& request = configuration.ifc_req[i];
  228. struct sockaddr* addr = &request.ifr_ifru.ifru_addr;
  229. if (addr->sa_family != AF_INET) continue;
  230. std::string ifname = request.ifr_ifrn.ifrn_name;
  231. // name can either be just interface name or interface name followed by ':' and arbitrary label
  232. if (ifname.find(':') != std::string::npos)
  233. ifname = ifname.substr(0, ifname.find(':'));
  234. InetAddress ip(&(((struct sockaddr_in *)addr)->sin_addr),4,0);
  235. if (ifChecker.shouldBindInterface(ifname.c_str(), ip)) {
  236. switch(ip.ipScope()) {
  237. default: break;
  238. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  239. case InetAddress::IP_SCOPE_GLOBAL:
  240. case InetAddress::IP_SCOPE_SHARED:
  241. case InetAddress::IP_SCOPE_PRIVATE:
  242. for(int x=0;x<portCount;++x) {
  243. ip.setPort(ports[x]);
  244. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,ifname));
  245. }
  246. break;
  247. }
  248. }
  249. }
  250. ip4_address_error:
  251. free(configuration.ifc_buf);
  252. if (controlfd > 0) close(controlfd);
  253. }
  254. const bool gotViaProc = (localIfAddrs.size() > 0);
  255. #else
  256. const bool gotViaProc = false;
  257. #endif
  258. if (!gotViaProc) {
  259. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  260. struct ifaddrs *ifa;
  261. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  262. ifa = ifatbl;
  263. while (ifa) {
  264. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  265. InetAddress ip = *(ifa->ifa_addr);
  266. if (ifChecker.shouldBindInterface(ifa->ifa_name,ip)) {
  267. switch(ip.ipScope()) {
  268. default: break;
  269. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  270. case InetAddress::IP_SCOPE_GLOBAL:
  271. case InetAddress::IP_SCOPE_SHARED:
  272. case InetAddress::IP_SCOPE_PRIVATE:
  273. for(int x=0;x<portCount;++x) {
  274. ip.setPort(ports[x]);
  275. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(ifa->ifa_name)));
  276. }
  277. break;
  278. }
  279. }
  280. }
  281. ifa = ifa->ifa_next;
  282. }
  283. freeifaddrs(ifatbl);
  284. }
  285. }
  286. #endif
  287. // Default to binding to wildcard if we can't enumerate addresses
  288. if (localIfAddrs.empty()) {
  289. for(int x=0;x<(int)portCount;++x) {
  290. localIfAddrs.insert(std::pair<InetAddress,std::string>(InetAddress((uint32_t)0,ports[x]),std::string()));
  291. 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,ports[x]),std::string()));
  292. }
  293. }
  294. std::vector<_Binding> newBindings;
  295. // Save bindings that are still valid, close those that are not
  296. for(std::vector<_Binding>::iterator b(_bindings.begin());b!=_bindings.end();++b) {
  297. if (localIfAddrs.find(b->address) != localIfAddrs.end()) {
  298. newBindings.push_back(*b);
  299. } else {
  300. phy.close(b->udpSock,false);
  301. phy.close(b->tcpListenSock,false);
  302. }
  303. }
  304. // Create new bindings for those not already bound
  305. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  306. typename std::vector<_Binding>::const_iterator bi(newBindings.begin());
  307. while (bi != newBindings.end()) {
  308. if (bi->address == ii->first)
  309. break;
  310. ++bi;
  311. }
  312. if (bi == newBindings.end()) {
  313. udps = phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0,ZT_UDP_DESIRED_BUF_SIZE);
  314. tcps = phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0);
  315. if ((udps)&&(tcps)) {
  316. #ifdef __LINUX__
  317. // Bind Linux sockets to their device so routes tha we manage do not override physical routes (wish all platforms had this!)
  318. if (ii->second.length() > 0) {
  319. char tmp[256];
  320. Utils::scopy(tmp,sizeof(tmp),ii->second.c_str());
  321. int fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(udps);
  322. if (fd >= 0)
  323. setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp));
  324. fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(tcps);
  325. if (fd >= 0)
  326. setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp));
  327. }
  328. #endif // __LINUX__
  329. newBindings.push_back(_Binding());
  330. newBindings.back().udpSock = udps;
  331. newBindings.back().tcpListenSock = tcps;
  332. newBindings.back().address = ii->first;
  333. }
  334. }
  335. }
  336. _bindings.swap(newBindings);
  337. }
  338. /**
  339. * @return All currently bound local interface addresses
  340. */
  341. inline std::vector<InetAddress> allBoundLocalInterfaceAddresses() const
  342. {
  343. std::vector<InetAddress> aa;
  344. Mutex::Lock _l(_lock);
  345. for(std::vector<_Binding>::const_iterator b(_bindings.begin());b!=_bindings.end();++b)
  346. aa.push_back(b->address);
  347. return aa;
  348. }
  349. /**
  350. * Send from all bound UDP sockets
  351. */
  352. template<typename PHY_HANDLER_TYPE>
  353. inline bool udpSendAll(Phy<PHY_HANDLER_TYPE> &phy,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  354. {
  355. bool r = false;
  356. Mutex::Lock _l(_lock);
  357. for(std::vector<_Binding>::const_iterator b(_bindings.begin());b!=_bindings.end();++b) {
  358. if (ttl) phy.setIp4UdpTtl(b->udpSock,ttl);
  359. if (phy.udpSend(b->udpSock,(const struct sockaddr *)addr,data,len)) r = true;
  360. if (ttl) phy.setIp4UdpTtl(b->udpSock,255);
  361. }
  362. return r;
  363. }
  364. /**
  365. * @param addr Address to check
  366. * @return True if this is a bound local interface address
  367. */
  368. inline bool isBoundLocalInterfaceAddress(const InetAddress &addr) const
  369. {
  370. Mutex::Lock _l(_lock);
  371. for(std::vector<_Binding>::const_iterator b(_bindings.begin());b!=_bindings.end();++b) {
  372. if (b->address == addr)
  373. return true;
  374. }
  375. return false;
  376. }
  377. private:
  378. std::vector<_Binding> _bindings;
  379. Mutex _lock;
  380. };
  381. } // namespace ZeroTier
  382. #endif