Binder.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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_BINDER_HPP
  14. #define ZT_BINDER_HPP
  15. #include "../node/Constants.hpp"
  16. #include <stdint.h>
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #ifdef __WINDOWS__
  21. #include <WinSock2.h>
  22. #include <Windows.h>
  23. #include <ShlObj.h>
  24. #include <netioapi.h>
  25. #include <iphlpapi.h>
  26. #else
  27. #include <sys/types.h>
  28. #include <sys/socket.h>
  29. #include <sys/wait.h>
  30. #include <unistd.h>
  31. #include <ifaddrs.h>
  32. #ifdef __LINUX__
  33. #include <sys/ioctl.h>
  34. #include <net/if.h>
  35. #endif
  36. #endif
  37. #include <string>
  38. #include <vector>
  39. #include <algorithm>
  40. #include <utility>
  41. #include <map>
  42. #include <set>
  43. #include <atomic>
  44. #include "../node/InetAddress.hpp"
  45. #include "../node/Mutex.hpp"
  46. #include "../node/Utils.hpp"
  47. #include "Phy.hpp"
  48. #include "OSUtils.hpp"
  49. #if (defined(__amd64) || defined(__amd64__) || defined(__x86_64) || defined(__x86_64__) || defined(__AMD64) || defined(__AMD64__))
  50. #define ZT_UDP_DESIRED_BUF_SIZE 1048576
  51. #else
  52. #define ZT_UDP_DESIRED_BUF_SIZE 131072
  53. #endif
  54. // Period between refreshes of bindings
  55. #define ZT_BINDER_REFRESH_PERIOD 30000
  56. // Max number of bindings
  57. #define ZT_BINDER_MAX_BINDINGS 256
  58. namespace ZeroTier {
  59. /**
  60. * Enumerates local devices and binds to all potential ZeroTier path endpoints
  61. *
  62. * This replaces binding to wildcard (0.0.0.0 and ::0) with explicit binding
  63. * as part of the path to default gateway support. Under the hood it uses
  64. * different queries on different OSes to enumerate devices, and also exposes
  65. * device enumeration and endpoint IP data for use elsewhere.
  66. *
  67. * On OSes that do not support local port enumeration or where this is not
  68. * meaningful, this degrades to binding to wildcard.
  69. */
  70. class Binder
  71. {
  72. private:
  73. struct _Binding
  74. {
  75. _Binding() : udpSock((PhySocket *)0),tcpListenSock((PhySocket *)0) {}
  76. PhySocket *udpSock;
  77. PhySocket *tcpListenSock;
  78. InetAddress address;
  79. };
  80. public:
  81. Binder() : _bindingCount(0) {}
  82. /**
  83. * Close all bound ports, should be called on shutdown
  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(unsigned int b=0,c=_bindingCount;b<c;++b) {
  92. phy.close(_bindings[b].udpSock,false);
  93. phy.close(_bindings[b].tcpListenSock,false);
  94. }
  95. _bindingCount = 0;
  96. }
  97. /**
  98. * Scan local devices and addresses and rebind TCP and UDP
  99. *
  100. * This should be called after wake from sleep, on detected network device
  101. * changes, on startup, or periodically (e.g. every 30-60s).
  102. *
  103. * @param phy Physical interface
  104. * @param ports Ports to bind on all interfaces
  105. * @param portCount Number of ports
  106. * @param explicitBind If present, override interface IP detection and bind to these (if possible)
  107. * @param ifChecker Interface checker function to see if an interface should be used
  108. * @tparam PHY_HANDLER_TYPE Type for Phy<> template
  109. * @tparam INTERFACE_CHECKER Type for class containing shouldBindInterface() method
  110. */
  111. template<typename PHY_HANDLER_TYPE,typename INTERFACE_CHECKER>
  112. void refresh(Phy<PHY_HANDLER_TYPE> &phy,unsigned int *ports,unsigned int portCount,const std::vector<InetAddress> explicitBind,INTERFACE_CHECKER &ifChecker)
  113. {
  114. std::map<InetAddress,std::string> localIfAddrs;
  115. PhySocket *udps,*tcps;
  116. Mutex::Lock _l(_lock);
  117. bool interfacesEnumerated = true;
  118. if (explicitBind.empty()) {
  119. #ifdef __WINDOWS__
  120. char aabuf[32768];
  121. ULONG aalen = sizeof(aabuf);
  122. 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) {
  123. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  124. while (a) {
  125. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  126. while (ua) {
  127. InetAddress ip(ua->Address.lpSockaddr);
  128. if (ifChecker.shouldBindInterface("",ip)) {
  129. switch(ip.ipScope()) {
  130. default: break;
  131. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  132. case InetAddress::IP_SCOPE_GLOBAL:
  133. case InetAddress::IP_SCOPE_SHARED:
  134. case InetAddress::IP_SCOPE_PRIVATE:
  135. for(int x=0;x<(int)portCount;++x) {
  136. ip.setPort(ports[x]);
  137. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string()));
  138. }
  139. break;
  140. }
  141. }
  142. ua = ua->Next;
  143. }
  144. a = a->Next;
  145. }
  146. }
  147. else {
  148. interfacesEnumerated = false;
  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. else {
  175. interfacesEnumerated = false;
  176. }
  177. // Get IPv6 addresses (and any device names we don't already know)
  178. OSUtils::ztsnprintf(fn,sizeof(fn),"/proc/%lu/net/if_inet6",pid);
  179. procf = fopen(fn,"r");
  180. if (procf) {
  181. while (fgets(tmp,sizeof(tmp),procf)) {
  182. tmp[255] = 0;
  183. char *saveptr = (char *)0;
  184. unsigned char ipbits[16];
  185. memset(ipbits,0,sizeof(ipbits));
  186. char *devname = (char *)0;
  187. int n = 0;
  188. for(char *f=Utils::stok(tmp," \t\r\n",&saveptr);(f);f=Utils::stok((char *)0," \t\r\n",&saveptr)) {
  189. switch(n++) {
  190. case 0: // IP in hex
  191. Utils::unhex(f,32,ipbits,16);
  192. break;
  193. case 5: // device name
  194. devname = f;
  195. break;
  196. }
  197. }
  198. if (devname) {
  199. ifnames.insert(devname);
  200. InetAddress ip(ipbits,16,0);
  201. if (ifChecker.shouldBindInterface(devname,ip)) {
  202. switch(ip.ipScope()) {
  203. default: break;
  204. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  205. case InetAddress::IP_SCOPE_GLOBAL:
  206. case InetAddress::IP_SCOPE_SHARED:
  207. case InetAddress::IP_SCOPE_PRIVATE:
  208. for(int x=0;x<(int)portCount;++x) {
  209. ip.setPort(ports[x]);
  210. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(devname)));
  211. }
  212. break;
  213. }
  214. }
  215. }
  216. }
  217. fclose(procf);
  218. }
  219. // Get IPv4 addresses for each device
  220. if (ifnames.size() > 0) {
  221. const int controlfd = (int)socket(AF_INET,SOCK_DGRAM,0);
  222. struct ifconf configuration;
  223. configuration.ifc_len = 0;
  224. configuration.ifc_buf = nullptr;
  225. if (controlfd < 0) goto ip4_address_error;
  226. if (ioctl(controlfd, SIOCGIFCONF, &configuration) < 0) goto ip4_address_error;
  227. configuration.ifc_buf = (char*)malloc(configuration.ifc_len);
  228. if (ioctl(controlfd, SIOCGIFCONF, &configuration) < 0) goto ip4_address_error;
  229. for (int i=0; i < (int)(configuration.ifc_len / sizeof(ifreq)); i ++) {
  230. struct ifreq& request = configuration.ifc_req[i];
  231. struct sockaddr* addr = &request.ifr_ifru.ifru_addr;
  232. if (addr->sa_family != AF_INET) continue;
  233. std::string ifname = request.ifr_ifrn.ifrn_name;
  234. // name can either be just interface name or interface name followed by ':' and arbitrary label
  235. if (ifname.find(':') != std::string::npos)
  236. ifname = ifname.substr(0, ifname.find(':'));
  237. InetAddress ip(&(((struct sockaddr_in *)addr)->sin_addr),4,0);
  238. if (ifChecker.shouldBindInterface(ifname.c_str(), ip)) {
  239. switch(ip.ipScope()) {
  240. default: break;
  241. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  242. case InetAddress::IP_SCOPE_GLOBAL:
  243. case InetAddress::IP_SCOPE_SHARED:
  244. case InetAddress::IP_SCOPE_PRIVATE:
  245. for(int x=0;x<(int)portCount;++x) {
  246. ip.setPort(ports[x]);
  247. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,ifname));
  248. }
  249. break;
  250. }
  251. }
  252. }
  253. ip4_address_error:
  254. free(configuration.ifc_buf);
  255. if (controlfd > 0) close(controlfd);
  256. }
  257. const bool gotViaProc = (localIfAddrs.size() > 0);
  258. #else
  259. const bool gotViaProc = false;
  260. #endif
  261. #if !defined(ZT_SDK) || !defined(__ANDROID__) // getifaddrs() freeifaddrs() not available on Android
  262. if (!gotViaProc) {
  263. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  264. struct ifaddrs *ifa;
  265. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  266. ifa = ifatbl;
  267. while (ifa) {
  268. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  269. InetAddress ip = *(ifa->ifa_addr);
  270. if (ifChecker.shouldBindInterface(ifa->ifa_name,ip)) {
  271. switch(ip.ipScope()) {
  272. default: break;
  273. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  274. case InetAddress::IP_SCOPE_GLOBAL:
  275. case InetAddress::IP_SCOPE_SHARED:
  276. case InetAddress::IP_SCOPE_PRIVATE:
  277. for(int x=0;x<(int)portCount;++x) {
  278. ip.setPort(ports[x]);
  279. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(ifa->ifa_name)));
  280. }
  281. break;
  282. }
  283. }
  284. }
  285. ifa = ifa->ifa_next;
  286. }
  287. freeifaddrs(ifatbl);
  288. }
  289. else {
  290. interfacesEnumerated = false;
  291. }
  292. }
  293. #endif
  294. #endif
  295. } else {
  296. for(std::vector<InetAddress>::const_iterator i(explicitBind.begin());i!=explicitBind.end();++i)
  297. localIfAddrs.insert(std::pair<InetAddress,std::string>(*i,std::string()));
  298. }
  299. // Default to binding to wildcard if we can't enumerate addresses
  300. if (!interfacesEnumerated && localIfAddrs.empty()) {
  301. for(int x=0;x<(int)portCount;++x) {
  302. localIfAddrs.insert(std::pair<InetAddress,std::string>(InetAddress((uint32_t)0,ports[x]),std::string()));
  303. 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()));
  304. }
  305. }
  306. const unsigned int oldBindingCount = _bindingCount;
  307. _bindingCount = 0;
  308. // Save bindings that are still valid, close those that are not
  309. for(unsigned int b=0;b<oldBindingCount;++b) {
  310. if (localIfAddrs.find(_bindings[b].address) != localIfAddrs.end()) {
  311. if (_bindingCount != b)
  312. _bindings[(unsigned int)_bindingCount] = _bindings[b];
  313. ++_bindingCount;
  314. } else {
  315. PhySocket *const udps = _bindings[b].udpSock;
  316. PhySocket *const tcps = _bindings[b].tcpListenSock;
  317. _bindings[b].udpSock = (PhySocket *)0;
  318. _bindings[b].tcpListenSock = (PhySocket *)0;
  319. phy.close(udps,false);
  320. phy.close(tcps,false);
  321. }
  322. }
  323. // Create new bindings for those not already bound
  324. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  325. unsigned int bi = 0;
  326. while (bi != _bindingCount) {
  327. if (_bindings[bi].address == ii->first)
  328. break;
  329. ++bi;
  330. }
  331. if (bi == _bindingCount) {
  332. udps = phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0,ZT_UDP_DESIRED_BUF_SIZE);
  333. tcps = phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0);
  334. if ((udps)&&(tcps)) {
  335. #ifdef __LINUX__
  336. // Bind Linux sockets to their device so routes that we manage do not override physical routes (wish all platforms had this!)
  337. if (ii->second.length() > 0) {
  338. char tmp[256];
  339. Utils::scopy(tmp,sizeof(tmp),ii->second.c_str());
  340. int fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(udps);
  341. if (fd >= 0)
  342. setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp));
  343. fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(tcps);
  344. if (fd >= 0)
  345. setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp));
  346. }
  347. #endif // __LINUX__
  348. if (_bindingCount < ZT_BINDER_MAX_BINDINGS) {
  349. _bindings[_bindingCount].udpSock = udps;
  350. _bindings[_bindingCount].tcpListenSock = tcps;
  351. _bindings[_bindingCount].address = ii->first;
  352. phy.setIfName(udps,(char*)ii->second.c_str(),(int)ii->second.length());
  353. ++_bindingCount;
  354. }
  355. } else {
  356. phy.close(udps,false);
  357. phy.close(tcps,false);
  358. }
  359. }
  360. }
  361. }
  362. /**
  363. * @return All currently bound local interface addresses
  364. */
  365. inline std::vector<InetAddress> allBoundLocalInterfaceAddresses() const
  366. {
  367. std::vector<InetAddress> aa;
  368. Mutex::Lock _l(_lock);
  369. for(unsigned int b=0,c=_bindingCount;b<c;++b)
  370. aa.push_back(_bindings[b].address);
  371. return aa;
  372. }
  373. /**
  374. * Send from all bound UDP sockets
  375. */
  376. template<typename PHY_HANDLER_TYPE>
  377. inline bool udpSendAll(Phy<PHY_HANDLER_TYPE> &phy,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  378. {
  379. bool r = false;
  380. Mutex::Lock _l(_lock);
  381. for(unsigned int b=0,c=_bindingCount;b<c;++b) {
  382. if (ttl) phy.setIp4UdpTtl(_bindings[b].udpSock,ttl);
  383. if (phy.udpSend(_bindings[b].udpSock,(const struct sockaddr *)addr,data,len)) r = true;
  384. if (ttl) phy.setIp4UdpTtl(_bindings[b].udpSock,255);
  385. }
  386. return r;
  387. }
  388. /**
  389. * @param addr Address to check
  390. * @return True if this is a bound local interface address
  391. */
  392. inline bool isBoundLocalInterfaceAddress(const InetAddress &addr) const
  393. {
  394. Mutex::Lock _l(_lock);
  395. for(unsigned int b=0;b<_bindingCount;++b) {
  396. if (_bindings[b].address == addr)
  397. return true;
  398. }
  399. return false;
  400. }
  401. /**
  402. * Quickly check that a UDP socket is valid
  403. *
  404. * @param udpSock UDP socket to check
  405. * @return True if socket is currently bound/allocated
  406. */
  407. inline bool isUdpSocketValid(PhySocket *const udpSock)
  408. {
  409. for(unsigned int b=0,c=_bindingCount;b<c;++b) {
  410. if (_bindings[b].udpSock == udpSock)
  411. return (b < _bindingCount); // double check atomic which may have changed
  412. }
  413. return false;
  414. }
  415. private:
  416. _Binding _bindings[ZT_BINDER_MAX_BINDINGS];
  417. std::atomic<unsigned int> _bindingCount;
  418. Mutex _lock;
  419. };
  420. } // namespace ZeroTier
  421. #endif