BSDEthernetTap.cpp 14 KB

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