BSDEthernetTap.cpp 13 KB

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