LinuxEthernetTap.cpp 14 KB

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