Binder.hpp 16 KB

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