Binder.hpp 16 KB

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