BSDEthernetTap.cpp 14 KB

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