LinuxEthernetTap.cpp 15 KB

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