BSDEthernetTap.cpp 14 KB

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