Binder.hpp 17 KB

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