LinuxEthernetTap.cpp 15 KB

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