Binder.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. char strBuf[128] = { 0 };
  124. wcstombs(strBuf, a->FriendlyName, sizeof(strBuf));
  125. if (ifChecker.shouldBindInterface(strBuf,ip)) {
  126. switch(ip.ipScope()) {
  127. default: break;
  128. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  129. case InetAddress::IP_SCOPE_GLOBAL:
  130. case InetAddress::IP_SCOPE_SHARED:
  131. case InetAddress::IP_SCOPE_PRIVATE:
  132. for(int x=0;x<(int)portCount;++x) {
  133. ip.setPort(ports[x]);
  134. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string()));
  135. }
  136. break;
  137. }
  138. }
  139. ua = ua->Next;
  140. }
  141. a = a->Next;
  142. }
  143. }
  144. else {
  145. interfacesEnumerated = false;
  146. }
  147. #else // not __WINDOWS__
  148. /* On Linux we use an alternative method if available since getifaddrs()
  149. * gets very slow when there are lots of network namespaces. This won't
  150. * work unless /proc/PID/net/if_inet6 exists and it may not on some
  151. * embedded systems, so revert to getifaddrs() there. */
  152. #ifdef __LINUX__
  153. char fn[256],tmp[256];
  154. std::set<std::string> ifnames;
  155. const unsigned long pid = (unsigned long)getpid();
  156. // Get all device names
  157. OSUtils::ztsnprintf(fn,sizeof(fn),"/proc/%lu/net/dev",pid);
  158. FILE *procf = fopen(fn,"r");
  159. if (procf) {
  160. while (fgets(tmp,sizeof(tmp),procf)) {
  161. tmp[255] = 0;
  162. char *saveptr = (char *)0;
  163. for(char *f=Utils::stok(tmp," \t\r\n:|",&saveptr);(f);f=Utils::stok((char *)0," \t\r\n:|",&saveptr)) {
  164. if ((strcmp(f,"Inter-") != 0)&&(strcmp(f,"face") != 0)&&(f[0] != 0))
  165. ifnames.insert(f);
  166. break; // we only want the first field
  167. }
  168. }
  169. fclose(procf);
  170. }
  171. else {
  172. interfacesEnumerated = false;
  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<(int)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.empty()) {
  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<(int)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.empty());
  255. #else
  256. const bool gotViaProc = false;
  257. #endif
  258. #if !defined(ZT_SDK) || !defined(__ANDROID__) // getifaddrs() freeifaddrs() not available on Android
  259. if (!gotViaProc) {
  260. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  261. struct ifaddrs *ifa;
  262. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  263. ifa = ifatbl;
  264. while (ifa) {
  265. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  266. InetAddress ip = *(ifa->ifa_addr);
  267. if (ifChecker.shouldBindInterface(ifa->ifa_name,ip)) {
  268. switch(ip.ipScope()) {
  269. default: break;
  270. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  271. case InetAddress::IP_SCOPE_GLOBAL:
  272. case InetAddress::IP_SCOPE_SHARED:
  273. case InetAddress::IP_SCOPE_PRIVATE:
  274. for(int x=0;x<(int)portCount;++x) {
  275. ip.setPort(ports[x]);
  276. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(ifa->ifa_name)));
  277. }
  278. break;
  279. }
  280. }
  281. }
  282. ifa = ifa->ifa_next;
  283. }
  284. freeifaddrs(ifatbl);
  285. }
  286. else {
  287. interfacesEnumerated = false;
  288. }
  289. }
  290. #endif
  291. #endif
  292. } else {
  293. for(std::vector<InetAddress>::const_iterator i(explicitBind.begin());i!=explicitBind.end();++i)
  294. localIfAddrs.insert(std::pair<InetAddress,std::string>(*i,std::string()));
  295. }
  296. // Default to binding to wildcard if we can't enumerate addresses
  297. if (!interfacesEnumerated && localIfAddrs.empty()) {
  298. for(int x=0;x<(int)portCount;++x) {
  299. localIfAddrs.insert(std::pair<InetAddress,std::string>(InetAddress((uint32_t)0,ports[x]),std::string()));
  300. 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()));
  301. }
  302. }
  303. const unsigned int oldBindingCount = _bindingCount;
  304. _bindingCount = 0;
  305. // Save bindings that are still valid, close those that are not
  306. for(unsigned int b=0;b<oldBindingCount;++b) {
  307. if (localIfAddrs.find(_bindings[b].address) != localIfAddrs.end()) {
  308. if (_bindingCount != b)
  309. _bindings[(unsigned int)_bindingCount] = _bindings[b];
  310. ++_bindingCount;
  311. } else {
  312. PhySocket *const udps = _bindings[b].udpSock;
  313. PhySocket *const tcps = _bindings[b].tcpListenSock;
  314. _bindings[b].udpSock = (PhySocket *)0;
  315. _bindings[b].tcpListenSock = (PhySocket *)0;
  316. phy.close(udps,false);
  317. phy.close(tcps,false);
  318. }
  319. }
  320. // Generate set of unique interface names (used for formation of logical link set in multipath code)
  321. // TODO: Could be gated not to run if multipath is not enabled.
  322. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  323. linkIfNames.insert(ii->second);
  324. }
  325. for (std::set<std::string>::iterator si(linkIfNames.begin());si!=linkIfNames.end();) {
  326. bool bFoundMatch = false;
  327. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  328. if (ii->second == *si) {
  329. bFoundMatch = true;
  330. break;
  331. }
  332. }
  333. if (!bFoundMatch) {
  334. linkIfNames.erase(si++);
  335. }
  336. else {
  337. ++si;
  338. }
  339. }
  340. // Create new bindings for those not already bound
  341. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  342. unsigned int bi = 0;
  343. while (bi != _bindingCount) {
  344. if (_bindings[bi].address == ii->first)
  345. break;
  346. ++bi;
  347. }
  348. if (bi == _bindingCount) {
  349. udps = phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0,ZT_UDP_DESIRED_BUF_SIZE);
  350. tcps = phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0);
  351. if ((udps)&&(tcps)) {
  352. #ifdef __LINUX__
  353. // Bind Linux sockets to their device so routes that we manage do not override physical routes (wish all platforms had this!)
  354. if (ii->second.length() > 0) {
  355. char tmp[256];
  356. Utils::scopy(tmp,sizeof(tmp),ii->second.c_str());
  357. int fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(udps);
  358. if (fd >= 0)
  359. setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp));
  360. fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(tcps);
  361. if (fd >= 0)
  362. setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp));
  363. }
  364. #endif // __LINUX__
  365. if (_bindingCount < ZT_BINDER_MAX_BINDINGS) {
  366. _bindings[_bindingCount].udpSock = udps;
  367. _bindings[_bindingCount].tcpListenSock = tcps;
  368. _bindings[_bindingCount].address = ii->first;
  369. phy.setIfName(udps,(char*)ii->second.c_str(),(int)ii->second.length());
  370. ++_bindingCount;
  371. }
  372. } else {
  373. phy.close(udps,false);
  374. phy.close(tcps,false);
  375. }
  376. }
  377. }
  378. }
  379. /**
  380. * @return All currently bound local interface addresses
  381. */
  382. inline std::vector<InetAddress> allBoundLocalInterfaceAddresses() const
  383. {
  384. std::vector<InetAddress> aa;
  385. Mutex::Lock _l(_lock);
  386. for(unsigned int b=0,c=_bindingCount;b<c;++b)
  387. aa.push_back(_bindings[b].address);
  388. return aa;
  389. }
  390. /**
  391. * Send from all bound UDP sockets
  392. */
  393. template<typename PHY_HANDLER_TYPE>
  394. inline bool udpSendAll(Phy<PHY_HANDLER_TYPE> &phy,const struct sockaddr_storage *addr,const void *data,unsigned int len,unsigned int ttl)
  395. {
  396. bool r = false;
  397. Mutex::Lock _l(_lock);
  398. for(unsigned int b=0,c=_bindingCount;b<c;++b) {
  399. if (ttl) phy.setIp4UdpTtl(_bindings[b].udpSock,ttl);
  400. if (phy.udpSend(_bindings[b].udpSock,(const struct sockaddr *)addr,data,len)) r = true;
  401. if (ttl) phy.setIp4UdpTtl(_bindings[b].udpSock,255);
  402. }
  403. return r;
  404. }
  405. /**
  406. * @param addr Address to check
  407. * @return True if this is a bound local interface address
  408. */
  409. inline bool isBoundLocalInterfaceAddress(const InetAddress &addr) const
  410. {
  411. Mutex::Lock _l(_lock);
  412. for(unsigned int b=0;b<_bindingCount;++b) {
  413. if (_bindings[b].address == addr)
  414. return true;
  415. }
  416. return false;
  417. }
  418. /**
  419. * Quickly check that a UDP socket is valid
  420. *
  421. * @param udpSock UDP socket to check
  422. * @return True if socket is currently bound/allocated
  423. */
  424. inline bool isUdpSocketValid(PhySocket *const udpSock)
  425. {
  426. for(unsigned int b=0,c=_bindingCount;b<c;++b) {
  427. if (_bindings[b].udpSock == udpSock)
  428. return (b < _bindingCount); // double check atomic which may have changed
  429. }
  430. return false;
  431. }
  432. inline std::set<std::string> getLinkInterfaceNames()
  433. {
  434. Mutex::Lock _l(_lock);
  435. return linkIfNames;
  436. }
  437. private:
  438. std::set<std::string> linkIfNames;
  439. _Binding _bindings[ZT_BINDER_MAX_BINDINGS];
  440. std::atomic<unsigned int> _bindingCount;
  441. Mutex _lock;
  442. };
  443. } // namespace ZeroTier
  444. #endif