NetBSDEthernetTap.cpp 13 KB

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