LinuxEthernetTap.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 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. #include <stdint.h>
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <string.h>
  30. #include <unistd.h>
  31. #include <signal.h>
  32. #include <fcntl.h>
  33. #include <errno.h>
  34. #include <sys/types.h>
  35. #include <sys/stat.h>
  36. #include <sys/ioctl.h>
  37. #include <sys/wait.h>
  38. #include <sys/select.h>
  39. #include <netinet/in.h>
  40. #include <net/if_arp.h>
  41. #include <arpa/inet.h>
  42. #include <linux/if.h>
  43. #include <linux/if_tun.h>
  44. #include <linux/if_addr.h>
  45. #include <linux/if_ether.h>
  46. #include <ifaddrs.h>
  47. #include <algorithm>
  48. #include <utility>
  49. #include <string>
  50. #include "../node/Constants.hpp"
  51. #include "../node/Utils.hpp"
  52. #include "../node/Mutex.hpp"
  53. #include "../node/Dictionary.hpp"
  54. #include "OSUtils.hpp"
  55. #include "LinuxEthernetTap.hpp"
  56. #include "LinuxNetLink.hpp"
  57. // ff:ff:ff:ff:ff:ff with no ADI
  58. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  59. namespace ZeroTier {
  60. static Mutex __tapCreateLock;
  61. static const char _base32_chars[32] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7' };
  62. static void _base32_5_to_8(const uint8_t *in,char *out)
  63. {
  64. out[0] = _base32_chars[(in[0]) >> 3];
  65. out[1] = _base32_chars[(in[0] & 0x07) << 2 | (in[1] & 0xc0) >> 6];
  66. out[2] = _base32_chars[(in[1] & 0x3e) >> 1];
  67. out[3] = _base32_chars[(in[1] & 0x01) << 4 | (in[2] & 0xf0) >> 4];
  68. out[4] = _base32_chars[(in[2] & 0x0f) << 1 | (in[3] & 0x80) >> 7];
  69. out[5] = _base32_chars[(in[3] & 0x7c) >> 2];
  70. out[6] = _base32_chars[(in[3] & 0x03) << 3 | (in[4] & 0xe0) >> 5];
  71. out[7] = _base32_chars[(in[4] & 0x1f)];
  72. }
  73. LinuxEthernetTap::LinuxEthernetTap(
  74. const char *homePath,
  75. const MAC &mac,
  76. unsigned int mtu,
  77. unsigned int metric,
  78. uint64_t nwid,
  79. const char *friendlyName,
  80. void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  81. void *arg) :
  82. _handler(handler),
  83. _arg(arg),
  84. _nwid(nwid),
  85. _homePath(homePath),
  86. _mtu(mtu),
  87. _fd(0),
  88. _enabled(true)
  89. {
  90. char procpath[128],nwids[32];
  91. struct stat sbuf;
  92. // ensure netlink connection is started
  93. (void)LinuxNetLink::getInstance();
  94. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  95. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  96. _fd = ::open("/dev/net/tun",O_RDWR);
  97. if (_fd <= 0) {
  98. _fd = ::open("/dev/tun",O_RDWR);
  99. if (_fd <= 0)
  100. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  101. }
  102. struct ifreq ifr;
  103. memset(&ifr,0,sizeof(ifr));
  104. // Restore device names from legacy devicemap, but for new devices we use a base32-based canonical naming
  105. std::map<std::string,std::string> globalDeviceMap;
  106. FILE *devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"r");
  107. if (devmapf) {
  108. char buf[256];
  109. while (fgets(buf,sizeof(buf),devmapf)) {
  110. char *x = (char *)0;
  111. char *y = (char *)0;
  112. char *saveptr = (char *)0;
  113. for(char *f=Utils::stok(buf,"\r\n=",&saveptr);(f);f=Utils::stok((char *)0,"\r\n=",&saveptr)) {
  114. if (!x) x = f;
  115. else if (!y) y = f;
  116. else break;
  117. }
  118. if ((x)&&(y)&&(x[0])&&(y[0]))
  119. globalDeviceMap[x] = y;
  120. }
  121. fclose(devmapf);
  122. }
  123. bool recalledDevice = false;
  124. std::map<std::string,std::string>::const_iterator gdmEntry = globalDeviceMap.find(nwids);
  125. if (gdmEntry != globalDeviceMap.end()) {
  126. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),gdmEntry->second.c_str());
  127. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  128. recalledDevice = (stat(procpath,&sbuf) != 0);
  129. }
  130. if (!recalledDevice) {
  131. #ifdef __SYNOLOGY__
  132. int devno = 50;
  133. do {
  134. OSUtils::ztsnprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"eth%d",devno++);
  135. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  136. } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist
  137. #else
  138. uint64_t trial = 0; // incremented in the very unlikely event of a name collision with another network
  139. do {
  140. const uint64_t nwid40 = (nwid ^ (nwid >> 24)) + trial++;
  141. uint8_t tmp2[5];
  142. char tmp3[11];
  143. tmp2[0] = (uint8_t)((nwid40 >> 32) & 0xff);
  144. tmp2[1] = (uint8_t)((nwid40 >> 24) & 0xff);
  145. tmp2[2] = (uint8_t)((nwid40 >> 16) & 0xff);
  146. tmp2[3] = (uint8_t)((nwid40 >> 8) & 0xff);
  147. tmp2[4] = (uint8_t)(nwid40 & 0xff);
  148. tmp3[0] = 'z';
  149. tmp3[1] = 't';
  150. _base32_5_to_8(tmp2,tmp3 + 2);
  151. tmp3[10] = (char)0;
  152. memcpy(ifr.ifr_name,tmp3,11);
  153. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  154. } while (stat(procpath,&sbuf) == 0);
  155. #endif
  156. }
  157. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  158. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  159. ::close(_fd);
  160. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  161. }
  162. _dev = ifr.ifr_name;
  163. ::ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  164. // Open an arbitrary socket to talk to netlink
  165. int sock = socket(AF_INET,SOCK_DGRAM,0);
  166. if (sock <= 0) {
  167. ::close(_fd);
  168. throw std::runtime_error("unable to open netlink socket");
  169. }
  170. // Set MAC address
  171. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  172. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  173. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  174. ::close(_fd);
  175. ::close(sock);
  176. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  177. return;
  178. }
  179. // Set MTU
  180. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  181. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  182. ::close(_fd);
  183. ::close(sock);
  184. throw std::runtime_error("unable to configure TAP MTU");
  185. }
  186. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  187. ::close(_fd);
  188. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  189. }
  190. /* Bring interface up */
  191. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  192. ::close(_fd);
  193. ::close(sock);
  194. throw std::runtime_error("unable to get TAP interface flags");
  195. }
  196. ifr.ifr_flags |= IFF_UP;
  197. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  198. ::close(_fd);
  199. ::close(sock);
  200. throw std::runtime_error("unable to set TAP interface flags");
  201. }
  202. ::close(sock);
  203. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  204. ::fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  205. (void)::pipe(_shutdownSignalPipe);
  206. /*
  207. globalDeviceMap[nwids] = _dev;
  208. devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"w");
  209. if (devmapf) {
  210. gdmEntry = globalDeviceMap.begin();
  211. while (gdmEntry != globalDeviceMap.end()) {
  212. fprintf(devmapf,"%s=%s\n",gdmEntry->first.c_str(),gdmEntry->second.c_str());
  213. ++gdmEntry;
  214. }
  215. fclose(devmapf);
  216. }
  217. */
  218. _thread = Thread::start(this);
  219. }
  220. LinuxEthernetTap::~LinuxEthernetTap()
  221. {
  222. (void)::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  223. Thread::join(_thread);
  224. ::close(_fd);
  225. ::close(_shutdownSignalPipe[0]);
  226. ::close(_shutdownSignalPipe[1]);
  227. }
  228. void LinuxEthernetTap::setEnabled(bool en)
  229. {
  230. _enabled = en;
  231. }
  232. bool LinuxEthernetTap::enabled() const
  233. {
  234. return _enabled;
  235. }
  236. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  237. {
  238. LinuxNetLink::getInstance().removeAddress(ip, _dev.c_str());
  239. return true;
  240. }
  241. #ifdef __SYNOLOGY__
  242. bool LinuxEthernetTap::addIpSyn(std::vector<InetAddress> ips)
  243. {
  244. // Here we fill out interface config (ifcfg-dev) to prevent it from being killed
  245. std::string filepath = "/etc/sysconfig/network-scripts/ifcfg-"+_dev;
  246. std::string cfg_contents = "DEVICE="+_dev+"\nBOOTPROTO=static";
  247. int ip4=0,ip6=0,ip4_tot=0,ip6_tot=0;
  248. for(int i=0; i<(int)ips.size(); i++) {
  249. if (ips[i].isV4())
  250. ip4_tot++;
  251. else
  252. ip6_tot++;
  253. }
  254. // Assemble and write contents of ifcfg-dev file
  255. for(int i=0; i<(int)ips.size(); i++) {
  256. if (ips[i].isV4()) {
  257. char iptmp[64],iptmp2[64];
  258. std::string numstr4 = ip4_tot > 1 ? std::to_string(ip4) : "";
  259. cfg_contents += "\nIPADDR"+numstr4+"="+ips[i].toIpString(iptmp)
  260. + "\nNETMASK"+numstr4+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  261. ip4++;
  262. } else {
  263. char iptmp[64],iptmp2[64];
  264. std::string numstr6 = ip6_tot > 1 ? std::to_string(ip6) : "";
  265. cfg_contents += "\nIPV6ADDR"+numstr6+"="+ips[i].toIpString(iptmp)
  266. + "\nNETMASK"+numstr6+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  267. ip6++;
  268. }
  269. }
  270. OSUtils::writeFile(filepath.c_str(), cfg_contents.c_str(), cfg_contents.length());
  271. // Finaly, add IPs
  272. for(int i=0; i<(int)ips.size(); i++){
  273. LinuxNetLink::getInstance().addAddress(ips[i], _dev.c_str());
  274. }
  275. return true;
  276. }
  277. #endif // __SYNOLOGY__
  278. bool LinuxEthernetTap::addIp(const InetAddress &ip)
  279. {
  280. if (!ip)
  281. return false;
  282. std::vector<InetAddress> allIps(ips());
  283. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  284. return true;
  285. // Remove and reconfigure if address is the same but netmask is different
  286. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  287. if (i->ipsEqual(ip))
  288. ___removeIp(_dev,*i);
  289. }
  290. LinuxNetLink::getInstance().addAddress(ip, _dev.c_str());
  291. return true;
  292. }
  293. bool LinuxEthernetTap::removeIp(const InetAddress &ip)
  294. {
  295. if (!ip)
  296. return true;
  297. std::vector<InetAddress> allIps(ips());
  298. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
  299. if (___removeIp(_dev,ip))
  300. return true;
  301. }
  302. return false;
  303. }
  304. std::vector<InetAddress> LinuxEthernetTap::ips() const
  305. {
  306. struct ifaddrs *ifa = (struct ifaddrs *)0;
  307. if (getifaddrs(&ifa))
  308. return std::vector<InetAddress>();
  309. std::vector<InetAddress> r;
  310. struct ifaddrs *p = ifa;
  311. while (p) {
  312. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  313. switch(p->ifa_addr->sa_family) {
  314. case AF_INET: {
  315. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  316. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  317. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  318. } break;
  319. case AF_INET6: {
  320. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  321. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  322. uint32_t b[4];
  323. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  324. r.push_back(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
  325. } break;
  326. }
  327. }
  328. p = p->ifa_next;
  329. }
  330. if (ifa)
  331. freeifaddrs(ifa);
  332. std::sort(r.begin(),r.end());
  333. r.erase(std::unique(r.begin(),r.end()),r.end());
  334. return r;
  335. }
  336. void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  337. {
  338. char putBuf[ZT_MAX_MTU + 64];
  339. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  340. to.copyTo(putBuf,6);
  341. from.copyTo(putBuf + 6,6);
  342. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  343. memcpy(putBuf + 14,data,len);
  344. len += 14;
  345. (void)::write(_fd,putBuf,len);
  346. }
  347. }
  348. std::string LinuxEthernetTap::deviceName() const
  349. {
  350. return _dev;
  351. }
  352. void LinuxEthernetTap::setFriendlyName(const char *friendlyName)
  353. {
  354. }
  355. void LinuxEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  356. {
  357. char *ptr,*ptr2;
  358. unsigned char mac[6];
  359. std::vector<MulticastGroup> newGroups;
  360. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  361. if (fd > 0) {
  362. char buf[131072];
  363. int n = (int)::read(fd,buf,sizeof(buf));
  364. if ((n > 0)&&(n < (int)sizeof(buf))) {
  365. buf[n] = (char)0;
  366. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  367. int fno = 0;
  368. char *devname = (char *)0;
  369. char *mcastmac = (char *)0;
  370. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  371. if (fno == 1)
  372. devname = f;
  373. else if (fno == 4)
  374. mcastmac = f;
  375. ++fno;
  376. }
  377. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  378. newGroups.push_back(MulticastGroup(MAC(mac,6),0));
  379. }
  380. }
  381. ::close(fd);
  382. }
  383. std::vector<InetAddress> allIps(ips());
  384. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  385. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  386. std::sort(newGroups.begin(),newGroups.end());
  387. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  388. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  389. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  390. added.push_back(*m);
  391. }
  392. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  393. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  394. removed.push_back(*m);
  395. }
  396. _multicastGroups.swap(newGroups);
  397. }
  398. void LinuxEthernetTap::setMtu(unsigned int mtu)
  399. {
  400. if (_mtu != mtu) {
  401. _mtu = mtu;
  402. int sock = socket(AF_INET,SOCK_DGRAM,0);
  403. if (sock > 0) {
  404. struct ifreq ifr;
  405. memset(&ifr,0,sizeof(ifr));
  406. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  407. ioctl(sock,SIOCSIFMTU,(void *)&ifr);
  408. close(sock);
  409. }
  410. }
  411. }
  412. void LinuxEthernetTap::threadMain()
  413. throw()
  414. {
  415. fd_set readfds,nullfds;
  416. MAC to,from;
  417. int n,nfds,r;
  418. char getBuf[ZT_MAX_MTU + 64];
  419. Thread::sleep(500);
  420. FD_ZERO(&readfds);
  421. FD_ZERO(&nullfds);
  422. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  423. r = 0;
  424. for(;;) {
  425. FD_SET(_shutdownSignalPipe[0],&readfds);
  426. FD_SET(_fd,&readfds);
  427. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  428. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  429. break;
  430. if (FD_ISSET(_fd,&readfds)) {
  431. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  432. if (n < 0) {
  433. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  434. break;
  435. } else {
  436. // Some tap drivers like to send the ethernet frame and the
  437. // payload in two chunks, so handle that by accumulating
  438. // data until we have at least a frame.
  439. r += n;
  440. if (r > 14) {
  441. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  442. r = _mtu + 14;
  443. if (_enabled) {
  444. to.setTo(getBuf,6);
  445. from.setTo(getBuf + 6,6);
  446. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  447. // TODO: VLAN support
  448. _handler(_arg,(void *)0,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  449. }
  450. r = 0;
  451. }
  452. }
  453. }
  454. }
  455. }
  456. } // namespace ZeroTier