LinuxEthernetTap.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 *,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. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  77. struct ifreq ifr;
  78. memset(&ifr,0,sizeof(ifr));
  79. // Try to recall our last device name, or pick an unused one if that fails.
  80. bool recalledDevice = false;
  81. std::string devmapbuf;
  82. Dictionary devmap;
  83. if (OSUtils::readFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmapbuf)) {
  84. devmap.fromString(devmapbuf);
  85. std::string desiredDevice(devmap.get(nwids,""));
  86. if (desiredDevice.length() > 2) {
  87. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),desiredDevice.c_str());
  88. Utils::snprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  89. recalledDevice = (stat(procpath,&sbuf) != 0);
  90. }
  91. }
  92. if (!recalledDevice) {
  93. int devno = 0;
  94. do {
  95. Utils::snprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"zt%d",devno++);
  96. Utils::snprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  97. } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist
  98. }
  99. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  100. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  101. ::close(_fd);
  102. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  103. }
  104. _dev = ifr.ifr_name;
  105. ::ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  106. // Open an arbitrary socket to talk to netlink
  107. int sock = socket(AF_INET,SOCK_DGRAM,0);
  108. if (sock <= 0) {
  109. ::close(_fd);
  110. throw std::runtime_error("unable to open netlink socket");
  111. }
  112. // Set MAC address
  113. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  114. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  115. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  116. ::close(_fd);
  117. ::close(sock);
  118. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  119. return;
  120. }
  121. // Set MTU
  122. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  123. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  124. ::close(_fd);
  125. ::close(sock);
  126. throw std::runtime_error("unable to configure TAP MTU");
  127. }
  128. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  129. ::close(_fd);
  130. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  131. }
  132. /* Bring interface up */
  133. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  134. ::close(_fd);
  135. ::close(sock);
  136. throw std::runtime_error("unable to get TAP interface flags");
  137. }
  138. ifr.ifr_flags |= IFF_UP;
  139. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  140. ::close(_fd);
  141. ::close(sock);
  142. throw std::runtime_error("unable to set TAP interface flags");
  143. }
  144. ::close(sock);
  145. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  146. ::fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  147. ::pipe(_shutdownSignalPipe);
  148. devmap[nwids] = _dev;
  149. OSUtils::writeFile((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),devmap.toString());
  150. _thread = Thread::start(this);
  151. }
  152. LinuxEthernetTap::~LinuxEthernetTap()
  153. {
  154. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  155. Thread::join(_thread);
  156. ::close(_fd);
  157. ::close(_shutdownSignalPipe[0]);
  158. ::close(_shutdownSignalPipe[1]);
  159. }
  160. void LinuxEthernetTap::setEnabled(bool en)
  161. {
  162. _enabled = en;
  163. }
  164. bool LinuxEthernetTap::enabled() const
  165. {
  166. return _enabled;
  167. }
  168. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  169. {
  170. long cpid = (long)vfork();
  171. if (cpid == 0) {
  172. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  173. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  174. ::execlp("ip","ip","addr","del",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  175. ::_exit(-1);
  176. } else {
  177. int exitcode = -1;
  178. ::waitpid(cpid,&exitcode,0);
  179. return (exitcode == 0);
  180. }
  181. }
  182. bool LinuxEthernetTap::addIp(const InetAddress &ip)
  183. {
  184. if (!ip)
  185. return false;
  186. std::vector<InetAddress> allIps(ips());
  187. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  188. return true;
  189. // Remove and reconfigure if address is the same but netmask is different
  190. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  191. if (i->ipsEqual(ip))
  192. ___removeIp(_dev,*i);
  193. }
  194. long cpid = (long)vfork();
  195. if (cpid == 0) {
  196. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  197. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  198. if (ip.isV4()) {
  199. ::execlp("ip","ip","addr","add",ip.toString().c_str(),"broadcast",ip.broadcast().toIpString().c_str(),"dev",_dev.c_str(),(const char *)0);
  200. } else {
  201. ::execlp("ip","ip","addr","add",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  202. }
  203. ::_exit(-1);
  204. } else if (cpid > 0) {
  205. int exitcode = -1;
  206. ::waitpid(cpid,&exitcode,0);
  207. return (exitcode == 0);
  208. }
  209. return false;
  210. }
  211. bool LinuxEthernetTap::removeIp(const InetAddress &ip)
  212. {
  213. if (!ip)
  214. return true;
  215. std::vector<InetAddress> allIps(ips());
  216. if (!std::binary_search(allIps.begin(),allIps.end(),ip)) {
  217. if (___removeIp(_dev,ip))
  218. return true;
  219. }
  220. return false;
  221. }
  222. std::vector<InetAddress> LinuxEthernetTap::ips() const
  223. {
  224. struct ifaddrs *ifa = (struct ifaddrs *)0;
  225. if (getifaddrs(&ifa))
  226. return std::vector<InetAddress>();
  227. std::vector<InetAddress> r;
  228. struct ifaddrs *p = ifa;
  229. while (p) {
  230. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  231. switch(p->ifa_addr->sa_family) {
  232. case AF_INET: {
  233. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  234. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  235. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  236. } break;
  237. case AF_INET6: {
  238. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  239. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  240. uint32_t b[4];
  241. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  242. 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])));
  243. } break;
  244. }
  245. }
  246. p = p->ifa_next;
  247. }
  248. if (ifa)
  249. freeifaddrs(ifa);
  250. std::sort(r.begin(),r.end());
  251. std::unique(r.begin(),r.end());
  252. return r;
  253. }
  254. void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  255. {
  256. char putBuf[8194];
  257. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  258. to.copyTo(putBuf,6);
  259. from.copyTo(putBuf + 6,6);
  260. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  261. memcpy(putBuf + 14,data,len);
  262. len += 14;
  263. ::write(_fd,putBuf,len);
  264. }
  265. }
  266. std::string LinuxEthernetTap::deviceName() const
  267. {
  268. return _dev;
  269. }
  270. void LinuxEthernetTap::setFriendlyName(const char *friendlyName)
  271. {
  272. }
  273. void LinuxEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  274. {
  275. char *ptr,*ptr2;
  276. unsigned char mac[6];
  277. std::vector<MulticastGroup> newGroups;
  278. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  279. if (fd > 0) {
  280. char buf[131072];
  281. int n = (int)::read(fd,buf,sizeof(buf));
  282. if ((n > 0)&&(n < (int)sizeof(buf))) {
  283. buf[n] = (char)0;
  284. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  285. int fno = 0;
  286. char *devname = (char *)0;
  287. char *mcastmac = (char *)0;
  288. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  289. if (fno == 1)
  290. devname = f;
  291. else if (fno == 4)
  292. mcastmac = f;
  293. ++fno;
  294. }
  295. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  296. newGroups.push_back(MulticastGroup(MAC(mac,6),0));
  297. }
  298. }
  299. ::close(fd);
  300. }
  301. std::vector<InetAddress> allIps(ips());
  302. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  303. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  304. std::sort(newGroups.begin(),newGroups.end());
  305. std::unique(newGroups.begin(),newGroups.end());
  306. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  307. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  308. added.push_back(*m);
  309. }
  310. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  311. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  312. removed.push_back(*m);
  313. }
  314. _multicastGroups.swap(newGroups);
  315. }
  316. void LinuxEthernetTap::threadMain()
  317. throw()
  318. {
  319. fd_set readfds,nullfds;
  320. MAC to,from;
  321. int n,nfds,r;
  322. char getBuf[8194];
  323. Thread::sleep(500);
  324. FD_ZERO(&readfds);
  325. FD_ZERO(&nullfds);
  326. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  327. r = 0;
  328. for(;;) {
  329. FD_SET(_shutdownSignalPipe[0],&readfds);
  330. FD_SET(_fd,&readfds);
  331. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  332. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  333. break;
  334. if (FD_ISSET(_fd,&readfds)) {
  335. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  336. if (n < 0) {
  337. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  338. break;
  339. } else {
  340. // Some tap drivers like to send the ethernet frame and the
  341. // payload in two chunks, so handle that by accumulating
  342. // data until we have at least a frame.
  343. r += n;
  344. if (r > 14) {
  345. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  346. r = _mtu + 14;
  347. if (_enabled) {
  348. to.setTo(getBuf,6);
  349. from.setTo(getBuf + 6,6);
  350. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  351. // TODO: VLAN support
  352. _handler(_arg,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  353. }
  354. r = 0;
  355. }
  356. }
  357. }
  358. }
  359. }
  360. } // namespace ZeroTier