NetBSDEthernetTap.cpp 13 KB

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