Binder.hpp 15 KB

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