LinuxEthernetTap.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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 <string>
  49. #include <map>
  50. #include <set>
  51. #include <algorithm>
  52. #include "../Constants.hpp"
  53. #include "../Utils.hpp"
  54. #include "../Mutex.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. // On startup, searches the path for required external utilities (which might vary by Linux distro)
  59. #define ZT_UNIX_IP_COMMAND 1
  60. class _CommandFinder
  61. {
  62. public:
  63. _CommandFinder()
  64. {
  65. _findCmd(ZT_UNIX_IP_COMMAND,"ip");
  66. }
  67. inline const char *operator[](int id) const
  68. throw()
  69. {
  70. std::map<int,std::string>::const_iterator c(_paths.find(id));
  71. if (c == _paths.end())
  72. return (const char *)0;
  73. return c->second.c_str();
  74. }
  75. private:
  76. inline void _findCmd(int id,const char *name)
  77. {
  78. char tmp[4096];
  79. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/sbin/%s",name);
  80. if (ZeroTier::Utils::fileExists(tmp)) {
  81. _paths[id] = tmp;
  82. return;
  83. }
  84. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/usr/sbin/%s",name);
  85. if (ZeroTier::Utils::fileExists(tmp)) {
  86. _paths[id] = tmp;
  87. return;
  88. }
  89. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/bin/%s",name);
  90. if (ZeroTier::Utils::fileExists(tmp)) {
  91. _paths[id] = tmp;
  92. return;
  93. }
  94. ZeroTier::Utils::snprintf(tmp,sizeof(tmp),"/usr/bin/%s",name);
  95. if (ZeroTier::Utils::fileExists(tmp)) {
  96. _paths[id] = tmp;
  97. return;
  98. }
  99. }
  100. std::map<int,std::string> _paths;
  101. };
  102. static const _CommandFinder UNIX_COMMANDS;
  103. namespace ZeroTier {
  104. // Only permit one tap to be opened concurrently across the entire process
  105. static Mutex __tapCreateLock;
  106. LinuxEthernetTap::LinuxEthernetTap(
  107. const RuntimeEnvironment *renv,
  108. const char *tryToGetDevice,
  109. const MAC &mac,
  110. unsigned int mtu,
  111. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  112. void *arg)
  113. throw(std::runtime_error) :
  114. EthernetTap("LinuxEthernetTap",mac,mtu),
  115. _r(renv),
  116. _handler(handler),
  117. _arg(arg),
  118. _fd(0),
  119. _enabled(true)
  120. {
  121. char procpath[128];
  122. struct stat sbuf;
  123. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  124. if (mtu > 4096)
  125. throw std::runtime_error("max tap MTU is 4096");
  126. _fd = ::open("/dev/net/tun",O_RDWR);
  127. if (_fd <= 0)
  128. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  129. struct ifreq ifr;
  130. memset(&ifr,0,sizeof(ifr));
  131. // Try to recall our last device name, or pick an unused one if that fails.
  132. bool recalledDevice = false;
  133. if ((tryToGetDevice)&&(tryToGetDevice[0])) {
  134. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),tryToGetDevice);
  135. Utils::snprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  136. recalledDevice = (stat(procpath,&sbuf) != 0);
  137. }
  138. if (!recalledDevice) {
  139. int devno = 0;
  140. do {
  141. Utils::snprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"zt%d",devno++);
  142. Utils::snprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  143. } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist
  144. }
  145. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  146. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  147. ::close(_fd);
  148. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  149. }
  150. _dev = ifr.ifr_name;
  151. ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  152. // Open an arbitrary socket to talk to netlink
  153. int sock = socket(AF_INET,SOCK_DGRAM,0);
  154. if (sock <= 0) {
  155. ::close(_fd);
  156. throw std::runtime_error("unable to open netlink socket");
  157. }
  158. // Set MAC address
  159. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  160. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  161. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  162. ::close(_fd);
  163. ::close(sock);
  164. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  165. return;
  166. }
  167. // Set MTU
  168. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  169. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  170. ::close(_fd);
  171. ::close(sock);
  172. throw std::runtime_error("unable to configure TAP MTU");
  173. }
  174. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  175. ::close(_fd);
  176. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  177. }
  178. /* Bring interface up */
  179. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  180. ::close(_fd);
  181. ::close(sock);
  182. throw std::runtime_error("unable to get TAP interface flags");
  183. }
  184. ifr.ifr_flags |= IFF_UP;
  185. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  186. ::close(_fd);
  187. ::close(sock);
  188. throw std::runtime_error("unable to set TAP interface flags");
  189. }
  190. ::close(sock);
  191. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  192. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  193. ::pipe(_shutdownSignalPipe);
  194. _thread = Thread::start(this);
  195. }
  196. LinuxEthernetTap::~LinuxEthernetTap()
  197. {
  198. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  199. Thread::join(_thread);
  200. ::close(_fd);
  201. ::close(_shutdownSignalPipe[0]);
  202. ::close(_shutdownSignalPipe[1]);
  203. }
  204. void LinuxEthernetTap::setEnabled(bool en)
  205. {
  206. _enabled = en;
  207. // TODO: interface status change
  208. }
  209. bool LinuxEthernetTap::enabled() const
  210. {
  211. return _enabled;
  212. }
  213. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  214. {
  215. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  216. if (!ipcmd)
  217. return false;
  218. long cpid = (long)vfork();
  219. if (cpid == 0) {
  220. execl(ipcmd,ipcmd,"addr","del",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  221. _exit(-1);
  222. } else {
  223. int exitcode = -1;
  224. waitpid(cpid,&exitcode,0);
  225. return (exitcode == 0);
  226. }
  227. }
  228. bool LinuxEthernetTap::addIP(const InetAddress &ip)
  229. {
  230. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  231. if (!ipcmd) {
  232. LOG("ERROR: could not configure IP address for %s: unable to find 'ip' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev.c_str());
  233. return false;
  234. }
  235. if (!ip)
  236. return false;
  237. std::set<InetAddress> allIps(ips());
  238. if (allIps.count(ip) > 0)
  239. return true;
  240. // Remove and reconfigure if address is the same but netmask is different
  241. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  242. if (i->ipsEqual(ip)) {
  243. if (___removeIp(_dev,*i)) {
  244. break;
  245. } else {
  246. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  247. }
  248. }
  249. }
  250. long cpid;
  251. if ((cpid = (long)vfork()) == 0) {
  252. execl(ipcmd,ipcmd,"addr","add",ip.toString().c_str(),"dev",_dev.c_str(),(const char *)0);
  253. _exit(-1);
  254. } else if (cpid > 0) {
  255. int exitcode = -1;
  256. waitpid(cpid,&exitcode,0);
  257. return (exitcode == 0);
  258. }
  259. return false;
  260. }
  261. bool LinuxEthernetTap::removeIP(const InetAddress &ip)
  262. {
  263. if (ips().count(ip) > 0) {
  264. if (___removeIp(_dev,ip))
  265. return true;
  266. }
  267. return false;
  268. }
  269. std::set<InetAddress> LinuxEthernetTap::ips() const
  270. {
  271. struct ifaddrs *ifa = (struct ifaddrs *)0;
  272. if (getifaddrs(&ifa))
  273. return std::set<InetAddress>();
  274. std::set<InetAddress> r;
  275. struct ifaddrs *p = ifa;
  276. while (p) {
  277. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  278. switch(p->ifa_addr->sa_family) {
  279. case AF_INET: {
  280. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  281. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  282. r.insert(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  283. } break;
  284. case AF_INET6: {
  285. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  286. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  287. uint32_t b[4];
  288. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  289. r.insert(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
  290. } break;
  291. }
  292. }
  293. p = p->ifa_next;
  294. }
  295. if (ifa)
  296. freeifaddrs(ifa);
  297. return r;
  298. }
  299. void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  300. {
  301. char putBuf[8194];
  302. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  303. to.copyTo(putBuf,6);
  304. from.copyTo(putBuf + 6,6);
  305. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  306. memcpy(putBuf + 14,data,len);
  307. len += 14;
  308. ::write(_fd,putBuf,len);
  309. }
  310. }
  311. std::string LinuxEthernetTap::deviceName() const
  312. {
  313. return _dev;
  314. }
  315. void LinuxEthernetTap::setFriendlyName(const char *friendlyName)
  316. {
  317. }
  318. bool LinuxEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  319. {
  320. char *ptr,*ptr2;
  321. unsigned char mac[6];
  322. std::set<MulticastGroup> newGroups;
  323. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  324. if (fd > 0) {
  325. char buf[131072];
  326. int n = (int)::read(fd,buf,sizeof(buf));
  327. if ((n > 0)&&(n < (int)sizeof(buf))) {
  328. buf[n] = (char)0;
  329. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  330. int fno = 0;
  331. char *devname = (char *)0;
  332. char *mcastmac = (char *)0;
  333. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  334. if (fno == 1)
  335. devname = f;
  336. else if (fno == 4)
  337. mcastmac = f;
  338. ++fno;
  339. }
  340. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  341. newGroups.insert(MulticastGroup(MAC(mac,6),0));
  342. }
  343. }
  344. ::close(fd);
  345. }
  346. {
  347. std::set<InetAddress> allIps(ips());
  348. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  349. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  350. }
  351. bool changed = false;
  352. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  353. if (!groups.count(*mg)) {
  354. groups.insert(*mg);
  355. changed = true;
  356. }
  357. }
  358. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  359. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  360. groups.erase(mg++);
  361. changed = true;
  362. } else ++mg;
  363. }
  364. return changed;
  365. }
  366. void LinuxEthernetTap::threadMain()
  367. throw()
  368. {
  369. fd_set readfds,nullfds;
  370. MAC to,from;
  371. int n,nfds,r;
  372. char getBuf[8194];
  373. Buffer<4096> data;
  374. // Wait for a moment after startup -- wait for Network to finish
  375. // constructing itself.
  376. Thread::sleep(500);
  377. FD_ZERO(&readfds);
  378. FD_ZERO(&nullfds);
  379. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  380. r = 0;
  381. for(;;) {
  382. FD_SET(_shutdownSignalPipe[0],&readfds);
  383. FD_SET(_fd,&readfds);
  384. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  385. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  386. break;
  387. if (FD_ISSET(_fd,&readfds)) {
  388. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  389. if (n < 0) {
  390. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  391. TRACE("unexpected error reading from tap: %s",strerror(errno));
  392. break;
  393. }
  394. } else {
  395. // Some tap drivers like to send the ethernet frame and the
  396. // payload in two chunks, so handle that by accumulating
  397. // data until we have at least a frame.
  398. r += n;
  399. if (r > 14) {
  400. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  401. r = _mtu + 14;
  402. if (_enabled) {
  403. to.setTo(getBuf,6);
  404. from.setTo(getBuf + 6,6);
  405. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  406. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  407. _handler(_arg,from,to,etherType,data);
  408. }
  409. r = 0;
  410. }
  411. }
  412. }
  413. }
  414. }
  415. } // namespace ZeroTier