2
0

LinuxEthernetTap.cpp 12 KB

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