Binder.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 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. #ifndef ZT_BINDER_HPP
  19. #define ZT_BINDER_HPP
  20. #include "../node/Constants.hpp"
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #ifdef __WINDOWS__
  26. #include <WinSock2.h>
  27. #include <Windows.h>
  28. #include <ShlObj.h>
  29. #include <netioapi.h>
  30. #include <iphlpapi.h>
  31. #else
  32. #include <sys/types.h>
  33. #include <sys/socket.h>
  34. #include <sys/wait.h>
  35. #include <unistd.h>
  36. #include <ifaddrs.h>
  37. #ifdef __LINUX__
  38. #include <sys/ioctl.h>
  39. #include <net/if.h>
  40. #endif
  41. #endif
  42. #include <string>
  43. #include <vector>
  44. #include <algorithm>
  45. #include <utility>
  46. #include <map>
  47. #include "../node/NonCopyable.hpp"
  48. #include "../node/InetAddress.hpp"
  49. #include "../node/Mutex.hpp"
  50. #include "../node/Utils.hpp"
  51. #include "Phy.hpp"
  52. #include "OSUtils.hpp"
  53. /**
  54. * Period between binder rescans/refreshes
  55. *
  56. * OneService also does this on detected restarts.
  57. */
  58. #define ZT_BINDER_REFRESH_PERIOD 30000
  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 : NonCopyable
  72. {
  73. private:
  74. struct _Binding
  75. {
  76. _Binding() :
  77. udpSock((PhySocket *)0),
  78. tcpListenSock((PhySocket *)0),
  79. address() {}
  80. PhySocket *udpSock;
  81. PhySocket *tcpListenSock;
  82. InetAddress address;
  83. };
  84. public:
  85. Binder() {}
  86. /**
  87. * Close all bound ports
  88. *
  89. * This should be called on shutdown. It closes listen sockets and UDP ports
  90. * but not TCP connections from any TCP listen sockets.
  91. *
  92. * @param phy Physical interface
  93. */
  94. template<typename PHY_HANDLER_TYPE>
  95. void closeAll(Phy<PHY_HANDLER_TYPE> &phy)
  96. {
  97. Mutex::Lock _l(_lock);
  98. for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
  99. phy.close(i->udpSock,false);
  100. phy.close(i->tcpListenSock,false);
  101. }
  102. }
  103. /**
  104. * Scan local devices and addresses and rebind TCP and UDP
  105. *
  106. * This should be called after wake from sleep, on detected network device
  107. * changes, on startup, or periodically (e.g. every 30-60s).
  108. *
  109. * @param phy Physical interface
  110. * @param port Port to bind to on all interfaces (TCP and UDP)
  111. * @param ignoreInterfacesByName Ignore these interfaces by name
  112. * @param ignoreInterfacesByNamePrefix Ignore these interfaces by name-prefix (starts-with, e.g. zt ignores zt*)
  113. * @param ignoreInterfacesByAddress Ignore these interfaces by address
  114. * @tparam PHY_HANDLER_TYPE Type for Phy<> template
  115. * @tparam INTERFACE_CHECKER Type for class containing shouldBindInterface() method
  116. */
  117. template<typename PHY_HANDLER_TYPE,typename INTERFACE_CHECKER>
  118. void refresh(Phy<PHY_HANDLER_TYPE> &phy,unsigned int port,INTERFACE_CHECKER &ifChecker)
  119. {
  120. std::map<InetAddress,std::string> localIfAddrs;
  121. PhySocket *udps;
  122. //PhySocket *tcps;
  123. Mutex::Lock _l(_lock);
  124. #ifdef __WINDOWS__
  125. char aabuf[32768];
  126. ULONG aalen = sizeof(aabuf);
  127. 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) {
  128. PIP_ADAPTER_ADDRESSES a = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  129. while (a) {
  130. PIP_ADAPTER_UNICAST_ADDRESS ua = a->FirstUnicastAddress;
  131. while (ua) {
  132. InetAddress ip(ua->Address.lpSockaddr);
  133. if (ifChecker.shouldBindInterface("",ip)) {
  134. switch(ip.ipScope()) {
  135. default: break;
  136. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  137. case InetAddress::IP_SCOPE_GLOBAL:
  138. case InetAddress::IP_SCOPE_SHARED:
  139. case InetAddress::IP_SCOPE_PRIVATE:
  140. ip.setPort(port);
  141. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string()));
  142. break;
  143. }
  144. }
  145. ua = ua->Next;
  146. }
  147. a = a->Next;
  148. }
  149. }
  150. #else // not __WINDOWS__
  151. /* On Linux we use an alternative method if available since getifaddrs()
  152. * gets very slow when there are lots of network namespaces. This won't
  153. * work unless /proc/PID/net/if_inet6 exists and it may not on some
  154. * embedded systems, so revert to getifaddrs() there. */
  155. #ifdef __LINUX__
  156. char fn[256],tmp[256];
  157. std::set<std::string> ifnames;
  158. const unsigned long pid = (unsigned long)getpid();
  159. // Get all device names
  160. Utils::snprintf(fn,sizeof(fn),"/proc/%lu/net/dev",pid);
  161. FILE *procf = fopen(fn,"r");
  162. if (procf) {
  163. while (fgets(tmp,sizeof(tmp),procf)) {
  164. tmp[255] = 0;
  165. char *saveptr = (char *)0;
  166. for(char *f=Utils::stok(tmp," \t\r\n:|",&saveptr);(f);f=Utils::stok((char *)0," \t\r\n:|",&saveptr)) {
  167. if ((strcmp(f,"Inter-") != 0)&&(strcmp(f,"face") != 0)&&(f[0] != 0))
  168. ifnames.insert(f);
  169. break; // we only want the first field
  170. }
  171. }
  172. fclose(procf);
  173. }
  174. // Get IPv6 addresses (and any device names we don't already know)
  175. Utils::snprintf(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. ip.setPort(port);
  206. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(devname)));
  207. break;
  208. }
  209. }
  210. }
  211. }
  212. fclose(procf);
  213. }
  214. // Get IPv4 addresses for each device
  215. if (ifnames.size() > 0) {
  216. const int controlfd = (int)socket(AF_INET,SOCK_DGRAM,0);
  217. if (controlfd >= 0) {
  218. for(std::set<std::string>::iterator devname(ifnames.begin());devname!=ifnames.end();++devname) {
  219. struct ifreq ifr;
  220. memset(&ifr,0,sizeof(ifr));
  221. ifr.ifr_addr.sa_family = AF_INET;
  222. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),devname->c_str());
  223. if (ioctl(controlfd,SIOCGIFADDR,&ifr) >= 0) {
  224. InetAddress ip(&(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr),4,0);
  225. if (ifChecker.shouldBindInterface(devname->c_str(),ip)) {
  226. switch(ip.ipScope()) {
  227. default: break;
  228. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  229. case InetAddress::IP_SCOPE_GLOBAL:
  230. case InetAddress::IP_SCOPE_SHARED:
  231. case InetAddress::IP_SCOPE_PRIVATE:
  232. ip.setPort(port);
  233. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,*devname));
  234. break;
  235. }
  236. }
  237. }
  238. }
  239. close(controlfd);
  240. }
  241. }
  242. const bool gotViaProc = (localIfAddrs.size() > 0);
  243. #else
  244. const bool gotViaProc = false;
  245. #endif
  246. if (!gotViaProc) {
  247. struct ifaddrs *ifatbl = (struct ifaddrs *)0;
  248. struct ifaddrs *ifa;
  249. if ((getifaddrs(&ifatbl) == 0)&&(ifatbl)) {
  250. ifa = ifatbl;
  251. while (ifa) {
  252. if ((ifa->ifa_name)&&(ifa->ifa_addr)) {
  253. InetAddress ip = *(ifa->ifa_addr);
  254. if (ifChecker.shouldBindInterface(ifa->ifa_name,ip)) {
  255. switch(ip.ipScope()) {
  256. default: break;
  257. case InetAddress::IP_SCOPE_PSEUDOPRIVATE:
  258. case InetAddress::IP_SCOPE_GLOBAL:
  259. case InetAddress::IP_SCOPE_SHARED:
  260. case InetAddress::IP_SCOPE_PRIVATE:
  261. ip.setPort(port);
  262. localIfAddrs.insert(std::pair<InetAddress,std::string>(ip,std::string(ifa->ifa_name)));
  263. break;
  264. }
  265. }
  266. }
  267. ifa = ifa->ifa_next;
  268. }
  269. freeifaddrs(ifatbl);
  270. }
  271. }
  272. #endif
  273. // Default to binding to wildcard if we can't enumerate addresses
  274. if (localIfAddrs.empty()) {
  275. localIfAddrs.insert(std::pair<InetAddress,std::string>(InetAddress((uint32_t)0,port),std::string()));
  276. 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,port),std::string()));
  277. }
  278. // Close any old bindings to anything that doesn't exist anymore
  279. for(typename std::vector<_Binding>::const_iterator bi(_bindings.begin());bi!=_bindings.end();++bi) {
  280. if (localIfAddrs.find(bi->address) == localIfAddrs.end()) {
  281. phy.close(bi->udpSock,false);
  282. phy.close(bi->tcpListenSock,false);
  283. }
  284. }
  285. std::vector<_Binding> newBindings;
  286. for(std::map<InetAddress,std::string>::const_iterator ii(localIfAddrs.begin());ii!=localIfAddrs.end();++ii) {
  287. typename std::vector<_Binding>::const_iterator bi(_bindings.begin());
  288. while (bi != _bindings.end()) {
  289. if (bi->address == ii->first) {
  290. newBindings.push_back(*bi);
  291. break;
  292. }
  293. ++bi;
  294. }
  295. if (bi == _bindings.end()) {
  296. udps = phy.udpBind(reinterpret_cast<const struct sockaddr *>(&(ii->first)),(void *)0,ZT_UDP_DESIRED_BUF_SIZE);
  297. if (udps) {
  298. //tcps = phy.tcpListen(reinterpret_cast<const struct sockaddr *>(&ii),(void *)0);
  299. //if (tcps) {
  300. #ifdef __LINUX__
  301. // Bind Linux sockets to their device so routes tha we manage do not override physical routes (wish all platforms had this!)
  302. if (ii->second.length() > 0) {
  303. int fd = (int)Phy<PHY_HANDLER_TYPE>::getDescriptor(udps);
  304. char tmp[256];
  305. Utils::scopy(tmp,sizeof(tmp),ii->second.c_str());
  306. if (fd >= 0) {
  307. if (setsockopt(fd,SOL_SOCKET,SO_BINDTODEVICE,tmp,strlen(tmp)) != 0) {
  308. fprintf(stderr,"WARNING: unable to set SO_BINDTODEVICE to bind %s to %s\n",ii->first.toIpString().c_str(),ii->second.c_str());
  309. }
  310. }
  311. }
  312. #endif // __LINUX__
  313. newBindings.push_back(_Binding());
  314. newBindings.back().udpSock = udps;
  315. //newBindings.back().tcpListenSock = tcps;
  316. newBindings.back().address = ii->first;
  317. //} else {
  318. // phy.close(udps,false);
  319. //}
  320. }
  321. }
  322. }
  323. // Swapping pointers and then letting the old one fall out of scope is faster than copying again
  324. _bindings.swap(newBindings);
  325. }
  326. /**
  327. * Send a UDP packet from the specified local interface, or all
  328. *
  329. * Unfortunately even by examining the routing table there is no ultimately
  330. * robust way to tell where we might reach another host that works in all
  331. * environments. As a result, we send packets with null (wildcard) local
  332. * addresses from *every* bound interface.
  333. *
  334. * These are typically initial HELLOs, path probes, etc., since normal
  335. * conversations will have a local endpoint address. So the cost is low and
  336. * if the peer is not reachable via that route then the packet will go
  337. * nowhere and nothing will happen.
  338. *
  339. * It will of course only send via interface bindings of the same socket
  340. * family. No point in sending V4 via V6 or vice versa.
  341. *
  342. * In any case on most hosts there's only one or two interfaces that we
  343. * will use, so none of this is particularly costly.
  344. *
  345. * @param local Local interface address or null address for 'all'
  346. * @param remote Remote address
  347. * @param data Data to send
  348. * @param len Length of data
  349. * @param v4ttl If non-zero, send this packet with the specified IP TTL (IPv4 only)
  350. */
  351. template<typename PHY_HANDLER_TYPE>
  352. inline bool udpSend(Phy<PHY_HANDLER_TYPE> &phy,const InetAddress &local,const InetAddress &remote,const void *data,unsigned int len,unsigned int v4ttl = 0) const
  353. {
  354. Mutex::Lock _l(_lock);
  355. if (local) {
  356. for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
  357. if (i->address == local) {
  358. if ((v4ttl)&&(local.ss_family == AF_INET))
  359. phy.setIp4UdpTtl(i->udpSock,v4ttl);
  360. const bool result = phy.udpSend(i->udpSock,reinterpret_cast<const struct sockaddr *>(&remote),data,len);
  361. if ((v4ttl)&&(local.ss_family == AF_INET))
  362. phy.setIp4UdpTtl(i->udpSock,255);
  363. return result;
  364. }
  365. }
  366. return false;
  367. } else {
  368. bool result = false;
  369. for(typename std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i) {
  370. if (i->address.ss_family == remote.ss_family) {
  371. if ((v4ttl)&&(remote.ss_family == AF_INET))
  372. phy.setIp4UdpTtl(i->udpSock,v4ttl);
  373. result |= phy.udpSend(i->udpSock,reinterpret_cast<const struct sockaddr *>(&remote),data,len);
  374. if ((v4ttl)&&(remote.ss_family == AF_INET))
  375. phy.setIp4UdpTtl(i->udpSock,255);
  376. }
  377. }
  378. return result;
  379. }
  380. }
  381. /**
  382. * @return All currently bound local interface addresses
  383. */
  384. inline std::vector<InetAddress> allBoundLocalInterfaceAddresses()
  385. {
  386. Mutex::Lock _l(_lock);
  387. std::vector<InetAddress> aa;
  388. for(std::vector<_Binding>::const_iterator i(_bindings.begin());i!=_bindings.end();++i)
  389. aa.push_back(i->address);
  390. return aa;
  391. }
  392. private:
  393. std::vector<_Binding> _bindings;
  394. Mutex _lock;
  395. };
  396. } // namespace ZeroTier
  397. #endif