LinuxEthernetTap.cpp 15 KB

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