BSDEthernetTap.cpp 13 KB

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