BSDEthernetTap.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 <errno.h>
  23. #include <unistd.h>
  24. #include <signal.h>
  25. #include <fcntl.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 <sys/cdefs.h>
  32. #include <sys/uio.h>
  33. #include <sys/param.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/socket.h>
  36. #include <netinet/in.h>
  37. #include <arpa/inet.h>
  38. #include <net/if.h>
  39. #include <ifaddrs.h>
  40. #include <net/if_arp.h>
  41. #include <net/if_dl.h>
  42. #include <net/if_media.h>
  43. #include <net/route.h>
  44. #include <string>
  45. #include <map>
  46. #include <set>
  47. #include <algorithm>
  48. #include <utility>
  49. #include "../node/Constants.hpp"
  50. #include "../node/Utils.hpp"
  51. #include "../node/Mutex.hpp"
  52. #include "OSUtils.hpp"
  53. #include "BSDEthernetTap.hpp"
  54. #define ZT_BASE32_CHARS "0123456789abcdefghijklmnopqrstuv"
  55. // ff:ff:ff:ff:ff:ff with no ADI
  56. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  57. namespace ZeroTier {
  58. BSDEthernetTap::BSDEthernetTap(
  59. const char *homePath,
  60. const MAC &mac,
  61. unsigned int mtu,
  62. unsigned int metric,
  63. uint64_t nwid,
  64. const char *friendlyName,
  65. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  66. void *arg) :
  67. _handler(handler),
  68. _arg(arg),
  69. _nwid(nwid),
  70. _mtu(mtu),
  71. _metric(metric),
  72. _fd(0),
  73. _enabled(true)
  74. {
  75. static Mutex globalTapCreateLock;
  76. char devpath[64],ethaddr[64],mtustr[32],metstr[32],tmpdevname[32];
  77. struct stat stattmp;
  78. // On FreeBSD at least we can rename, so use nwid to generate a deterministic unique zt#### name using base32
  79. // As a result we don't use desiredDevice
  80. _dev = "zt";
  81. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 60) & 0x1f)]);
  82. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 55) & 0x1f)]);
  83. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 50) & 0x1f)]);
  84. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 45) & 0x1f)]);
  85. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 40) & 0x1f)]);
  86. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 35) & 0x1f)]);
  87. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 30) & 0x1f)]);
  88. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 25) & 0x1f)]);
  89. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 20) & 0x1f)]);
  90. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 15) & 0x1f)]);
  91. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 10) & 0x1f)]);
  92. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)((nwid >> 5) & 0x1f)]);
  93. _dev.push_back(ZT_BASE32_CHARS[(unsigned long)(nwid & 0x1f)]);
  94. Mutex::Lock _gl(globalTapCreateLock);
  95. if (mtu > 2800)
  96. throw std::runtime_error("max tap MTU is 2800");
  97. // On BSD we create taps and they can have high numbers, so use ones starting
  98. // at 9993 to not conflict with other stuff. Then we rename it to zt<base32 of nwid>
  99. std::vector<std::string> devFiles(OSUtils::listDirectory("/dev"));
  100. for(int i=9993;i<(9993+128);++i) {
  101. Utils::snprintf(tmpdevname,sizeof(tmpdevname),"tap%d",i);
  102. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",tmpdevname);
  103. if (std::find(devFiles.begin(),devFiles.end(),std::string(tmpdevname)) == devFiles.end()) {
  104. long cpid = (long)vfork();
  105. if (cpid == 0) {
  106. ::execl("/sbin/ifconfig","/sbin/ifconfig",tmpdevname,"create",(const char *)0);
  107. ::_exit(-1);
  108. } else if (cpid > 0) {
  109. int exitcode = -1;
  110. ::waitpid(cpid,&exitcode,0);
  111. } else throw std::runtime_error("fork() failed");
  112. if (!stat(devpath,&stattmp)) {
  113. cpid = (long)vfork();
  114. if (cpid == 0) {
  115. ::execl("/sbin/ifconfig","/sbin/ifconfig",tmpdevname,"name",_dev.c_str(),(const char *)0);
  116. ::_exit(-1);
  117. } else if (cpid > 0) {
  118. int exitcode = -1;
  119. ::waitpid(cpid,&exitcode,0);
  120. if (exitcode)
  121. throw std::runtime_error("ifconfig rename operation failed");
  122. } else throw std::runtime_error("fork() failed");
  123. _fd = ::open(devpath,O_RDWR);
  124. if (_fd > 0)
  125. break;
  126. else throw std::runtime_error("unable to open created tap device");
  127. } else {
  128. throw std::runtime_error("cannot find /dev node for newly created tap device");
  129. }
  130. }
  131. }
  132. if (_fd <= 0)
  133. throw std::runtime_error("unable to open TAP device or no more devices available");
  134. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  135. ::close(_fd);
  136. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  137. }
  138. // Configure MAC address and MTU, bring interface up
  139. Utils::snprintf(ethaddr,sizeof(ethaddr),"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",(int)mac[0],(int)mac[1],(int)mac[2],(int)mac[3],(int)mac[4],(int)mac[5]);
  140. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  141. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  142. long cpid = (long)vfork();
  143. if (cpid == 0) {
  144. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  145. ::_exit(-1);
  146. } else if (cpid > 0) {
  147. int exitcode = -1;
  148. ::waitpid(cpid,&exitcode,0);
  149. if (exitcode) {
  150. ::close(_fd);
  151. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  152. }
  153. }
  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. _thread = Thread::start(this);
  158. }
  159. BSDEthernetTap::~BSDEthernetTap()
  160. {
  161. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  162. Thread::join(_thread);
  163. ::close(_fd);
  164. ::close(_shutdownSignalPipe[0]);
  165. ::close(_shutdownSignalPipe[1]);
  166. long cpid = (long)vfork();
  167. if (cpid == 0) {
  168. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"destroy",(const char *)0);
  169. ::_exit(-1);
  170. } else if (cpid > 0) {
  171. int exitcode = -1;
  172. ::waitpid(cpid,&exitcode,0);
  173. }
  174. }
  175. void BSDEthernetTap::setEnabled(bool en)
  176. {
  177. _enabled = en;
  178. }
  179. bool BSDEthernetTap::enabled() const
  180. {
  181. return _enabled;
  182. }
  183. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  184. {
  185. long cpid = (long)vfork();
  186. if (cpid == 0) {
  187. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  188. _exit(-1);
  189. } else if (cpid > 0) {
  190. int exitcode = -1;
  191. waitpid(cpid,&exitcode,0);
  192. return (exitcode == 0);
  193. }
  194. return false; // never reached, make compiler shut up about return value
  195. }
  196. bool BSDEthernetTap::addIp(const InetAddress &ip)
  197. {
  198. if (!ip)
  199. return false;
  200. std::vector<InetAddress> allIps(ips());
  201. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end())
  202. return true; // IP/netmask already assigned
  203. // Remove and reconfigure if address is the same but netmask is different
  204. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  205. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  206. if (___removeIp(_dev,*i))
  207. break;
  208. }
  209. }
  210. long cpid = (long)vfork();
  211. if (cpid == 0) {
  212. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  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 BSDEthernetTap::removeIp(const InetAddress &ip)
  222. {
  223. if (!ip)
  224. return false;
  225. std::vector<InetAddress> allIps(ips());
  226. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
  227. if (___removeIp(_dev,ip))
  228. return true;
  229. }
  230. return false;
  231. }
  232. std::vector<InetAddress> BSDEthernetTap::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 BSDEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  265. {
  266. char putBuf[4096];
  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 BSDEthernetTap::deviceName() const
  277. {
  278. return _dev;
  279. }
  280. void BSDEthernetTap::setFriendlyName(const char *friendlyName)
  281. {
  282. }
  283. void BSDEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  284. {
  285. std::vector<MulticastGroup> newGroups;
  286. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  287. if (!getifmaddrs(&ifmap)) {
  288. struct ifmaddrs *p = ifmap;
  289. while (p) {
  290. if (p->ifma_addr->sa_family == AF_LINK) {
  291. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  292. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  293. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  294. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  295. }
  296. p = p->ifma_next;
  297. }
  298. freeifmaddrs(ifmap);
  299. }
  300. std::vector<InetAddress> allIps(ips());
  301. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  302. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  303. std::sort(newGroups.begin(),newGroups.end());
  304. std::unique(newGroups.begin(),newGroups.end());
  305. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  306. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  307. added.push_back(*m);
  308. }
  309. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  310. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  311. removed.push_back(*m);
  312. }
  313. _multicastGroups.swap(newGroups);
  314. }
  315. /*
  316. bool BSDEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  317. {
  318. std::set<MulticastGroup> newGroups;
  319. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  320. if (!getifmaddrs(&ifmap)) {
  321. struct ifmaddrs *p = ifmap;
  322. while (p) {
  323. if (p->ifma_addr->sa_family == AF_LINK) {
  324. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  325. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  326. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  327. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  328. }
  329. p = p->ifma_next;
  330. }
  331. freeifmaddrs(ifmap);
  332. }
  333. {
  334. std::set<InetAddress> allIps(ips());
  335. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  336. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  337. }
  338. bool changed = false;
  339. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  340. if (!groups.count(*mg)) {
  341. groups.insert(*mg);
  342. changed = true;
  343. }
  344. }
  345. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  346. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  347. groups.erase(mg++);
  348. changed = true;
  349. } else ++mg;
  350. }
  351. return changed;
  352. }
  353. */
  354. void BSDEthernetTap::threadMain()
  355. throw()
  356. {
  357. fd_set readfds,nullfds;
  358. MAC to,from;
  359. int n,nfds,r;
  360. char getBuf[8194];
  361. // Wait for a moment after startup -- wait for Network to finish
  362. // constructing itself.
  363. Thread::sleep(500);
  364. FD_ZERO(&readfds);
  365. FD_ZERO(&nullfds);
  366. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  367. r = 0;
  368. for(;;) {
  369. FD_SET(_shutdownSignalPipe[0],&readfds);
  370. FD_SET(_fd,&readfds);
  371. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  372. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  373. break;
  374. if (FD_ISSET(_fd,&readfds)) {
  375. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  376. if (n < 0) {
  377. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  378. break;
  379. } else {
  380. // Some tap drivers like to send the ethernet frame and the
  381. // payload in two chunks, so handle that by accumulating
  382. // data until we have at least a frame.
  383. r += n;
  384. if (r > 14) {
  385. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  386. r = _mtu + 14;
  387. if (_enabled) {
  388. to.setTo(getBuf,6);
  389. from.setTo(getBuf + 6,6);
  390. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  391. // TODO: VLAN support
  392. _handler(_arg,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  393. }
  394. r = 0;
  395. }
  396. }
  397. }
  398. }
  399. }
  400. } // namespace ZeroTier