Binder.hpp 15 KB

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