MacEthernetTap.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 "../node/Constants.hpp"
  14. #ifdef __APPLE__
  15. #include "../node/Dictionary.hpp"
  16. #include "../node/Mutex.hpp"
  17. #include "../node/Utils.hpp"
  18. #include "MacDNSHelper.hpp"
  19. #include "MacEthernetTap.hpp"
  20. #include "MacEthernetTapAgent.h"
  21. #include "OSUtils.hpp"
  22. #include <algorithm>
  23. #include <arpa/inet.h>
  24. #include <errno.h>
  25. #include <fcntl.h>
  26. #include <filesystem>
  27. #include <ifaddrs.h>
  28. #include <map>
  29. #include <net/if.h>
  30. #include <net/if_dl.h>
  31. #include <net/route.h>
  32. #include <netinet/in.h>
  33. #include <set>
  34. #include <signal.h>
  35. #include <stdint.h>
  36. #include <stdio.h>
  37. #include <stdlib.h>
  38. #include <string.h>
  39. #include <string>
  40. #include <sys/cdefs.h>
  41. #include <sys/ioctl.h>
  42. #include <sys/param.h>
  43. #include <sys/select.h>
  44. #include <sys/socket.h>
  45. #include <sys/stat.h>
  46. #include <sys/sysctl.h>
  47. #include <sys/types.h>
  48. #include <sys/uio.h>
  49. #include <sys/wait.h>
  50. #include <unistd.h>
  51. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff), 0);
  52. #define MACOS_FETH_MAX_MTU_SYSCTL "net.link.fake.max_mtu"
  53. namespace ZeroTier {
  54. static Mutex globalTapCreateLock;
  55. static bool globalTapInitialized = false;
  56. static bool fethMaxMtuAdjusted = false;
  57. MacEthernetTap::MacEthernetTap(
  58. const char* homePath,
  59. const MAC& mac,
  60. unsigned int mtu,
  61. unsigned int metric,
  62. uint64_t nwid,
  63. const char* friendlyName,
  64. void (*handler)(void*, void*, uint64_t, const MAC&, const MAC&, unsigned int, unsigned int, const void* data, unsigned int len),
  65. void* arg)
  66. : _handler(handler)
  67. , _arg(arg)
  68. , _nwid(nwid)
  69. , _homePath(homePath)
  70. , _mtu(mtu)
  71. , _metric(metric)
  72. , _devNo(0)
  73. , _agentStdin(-1)
  74. , _agentStdout(-1)
  75. , _agentStderr(-1)
  76. , _agentStdin2(-1)
  77. , _agentStdout2(-1)
  78. , _agentStderr2(-1)
  79. , _agentPid(-1)
  80. , _enabled(true)
  81. , _lastIfAddrsUpdate(0)
  82. {
  83. char ethaddr[64], mtustr[16], devnostr[16], devstr[16], metricstr[16];
  84. 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]);
  85. OSUtils::ztsnprintf(mtustr, sizeof(mtustr), "%u", mtu);
  86. OSUtils::ztsnprintf(metricstr, sizeof(metricstr), "%u", metric);
  87. std::string agentPath(homePath);
  88. agentPath.push_back(ZT_PATH_SEPARATOR);
  89. agentPath.append("MacEthernetTapAgent");
  90. if (! OSUtils::fileExists(agentPath.c_str()))
  91. throw std::runtime_error("MacEthernetTapAgent not present in ZeroTier home");
  92. Mutex::Lock _gl(globalTapCreateLock); // only make one at a time
  93. if (! fethMaxMtuAdjusted) {
  94. fethMaxMtuAdjusted = true;
  95. int old_mtu = 0;
  96. size_t old_mtu_len = sizeof(old_mtu);
  97. int mtu = 10000;
  98. sysctlbyname(MACOS_FETH_MAX_MTU_SYSCTL, &old_mtu, &old_mtu_len, &mtu, sizeof(mtu));
  99. }
  100. // Destroy all feth devices on first tap start in case ZeroTier did not exit cleanly last time.
  101. // We leave interfaces less than feth100 alone in case something else is messing with feth devices.
  102. if (! globalTapInitialized) {
  103. globalTapInitialized = true;
  104. struct ifaddrs* ifa = (struct ifaddrs*)0;
  105. std::set<std::string> deleted;
  106. if (! getifaddrs(&ifa)) {
  107. struct ifaddrs* p = ifa;
  108. while (p) {
  109. int nameLen = (int)strlen(p->ifa_name);
  110. // Delete feth# from feth0 to feth9999, but don't touch >10000.
  111. if ((! strncmp(p->ifa_name, "feth", 4)) && (nameLen >= 5) && (nameLen <= 8) && (deleted.count(std::string(p->ifa_name)) == 0)) {
  112. deleted.insert(std::string(p->ifa_name));
  113. const char* args[4];
  114. args[0] = "/sbin/ifconfig";
  115. args[1] = p->ifa_name;
  116. args[2] = "destroy";
  117. args[3] = (char*)0;
  118. const pid_t pid = vfork();
  119. if (pid == 0) {
  120. execv(args[0], const_cast<char**>(args));
  121. _exit(-1);
  122. }
  123. else if (pid > 0) {
  124. int rv = 0;
  125. waitpid(pid, &rv, 0);
  126. }
  127. }
  128. p = p->ifa_next;
  129. }
  130. freeifaddrs(ifa);
  131. }
  132. }
  133. unsigned int devNo = 100 + ((nwid ^ (nwid >> 32) ^ (nwid >> 48)) % 4900);
  134. for (;;) {
  135. OSUtils::ztsnprintf(devnostr, sizeof(devnostr), "%u", devNo);
  136. OSUtils::ztsnprintf(devstr, sizeof(devstr), "feth%u", devNo);
  137. bool duplicate = false;
  138. struct ifaddrs* ifa = (struct ifaddrs*)0;
  139. if (! getifaddrs(&ifa)) {
  140. struct ifaddrs* p = ifa;
  141. while (p) {
  142. if (! strcmp(p->ifa_name, devstr)) {
  143. duplicate = true;
  144. break;
  145. }
  146. p = p->ifa_next;
  147. }
  148. freeifaddrs(ifa);
  149. }
  150. if (duplicate) {
  151. devNo = (devNo + 1) % 5000;
  152. if (devNo < 100)
  153. devNo = 100;
  154. }
  155. else {
  156. _dev = devstr;
  157. _devNo = devNo;
  158. break;
  159. }
  160. }
  161. if (::pipe(_shutdownSignalPipe))
  162. throw std::runtime_error("pipe creation failed");
  163. int agentStdin[2];
  164. int agentStdout[2];
  165. int agentStderr[2];
  166. if (::pipe(agentStdin))
  167. throw std::runtime_error("pipe creation failed");
  168. if (::pipe(agentStdout))
  169. throw std::runtime_error("pipe creation failed");
  170. if (::pipe(agentStderr))
  171. throw std::runtime_error("pipe creation failed");
  172. _agentStdin = agentStdin[1];
  173. _agentStdout = agentStdout[0];
  174. _agentStderr = agentStderr[0];
  175. _agentStdin2 = agentStdin[0];
  176. _agentStdout2 = agentStdout[1];
  177. _agentStderr2 = agentStderr[1];
  178. long apid = (long)fork();
  179. if (apid < 0) {
  180. throw std::runtime_error("fork failed");
  181. }
  182. else if (apid == 0) {
  183. ::dup2(agentStdin[0], STDIN_FILENO);
  184. ::dup2(agentStdout[1], STDOUT_FILENO);
  185. ::dup2(agentStderr[1], STDERR_FILENO);
  186. ::close(agentStdin[0]);
  187. ::close(agentStdin[1]);
  188. ::close(agentStdout[0]);
  189. ::close(agentStdout[1]);
  190. ::close(agentStderr[0]);
  191. ::close(agentStderr[1]);
  192. ::execl(agentPath.c_str(), agentPath.c_str(), devnostr, ethaddr, mtustr, metricstr, (char*)0);
  193. ::_exit(-1);
  194. }
  195. else {
  196. _agentPid = apid;
  197. // Wait up to 10 seconds for the subprocess to actually create the device. This prevents
  198. // things like routes from being created before the device exists.
  199. for (int waitLoops = 0;; ++waitLoops) {
  200. struct ifaddrs* ifa = (struct ifaddrs*)0;
  201. if (! getifaddrs(&ifa)) {
  202. struct ifaddrs* p = ifa;
  203. while (p) {
  204. if ((p->ifa_name) && (! strcmp(devstr, p->ifa_name))) {
  205. waitLoops = -1;
  206. break;
  207. }
  208. p = p->ifa_next;
  209. }
  210. freeifaddrs(ifa);
  211. }
  212. if (waitLoops == -1) {
  213. break;
  214. }
  215. else if (waitLoops >= 100) { // 10 seconds
  216. throw std::runtime_error("feth device creation timed out");
  217. }
  218. Thread::sleep(100);
  219. }
  220. }
  221. _thread = Thread::start(this);
  222. }
  223. MacEthernetTap::~MacEthernetTap()
  224. {
  225. char tmp[64];
  226. const char* args[4];
  227. pid_t pid0, pid1;
  228. MacDNSHelper::removeDNS(_nwid);
  229. MacDNSHelper::removeIps4(_nwid);
  230. MacDNSHelper::removeIps6(_nwid);
  231. Mutex::Lock _gl(globalTapCreateLock);
  232. ::write(_shutdownSignalPipe[1], "\0", 1); // causes thread to exit
  233. int ec = 0;
  234. ::kill(_agentPid, SIGKILL);
  235. ::waitpid(_agentPid, &ec, 0);
  236. args[0] = "/sbin/ifconfig";
  237. args[1] = _dev.c_str();
  238. args[2] = "destroy";
  239. args[3] = (char*)0;
  240. pid0 = vfork();
  241. if (pid0 == 0) {
  242. execv(args[0], const_cast<char**>(args));
  243. _exit(-1);
  244. }
  245. snprintf(tmp, sizeof(tmp), "feth%u", _devNo + 5000);
  246. // args[0] = "/sbin/ifconfig";
  247. args[1] = tmp;
  248. // args[2] = "destroy";
  249. // args[3] = (char *)0;
  250. pid1 = vfork();
  251. if (pid1 == 0) {
  252. execv(args[0], const_cast<char**>(args));
  253. _exit(-1);
  254. }
  255. if (pid0 > 0) {
  256. int rv = 0;
  257. waitpid(pid0, &rv, 0);
  258. }
  259. if (pid1 > 0) {
  260. int rv = 0;
  261. waitpid(pid1, &rv, 0);
  262. }
  263. Thread::join(_thread);
  264. }
  265. void MacEthernetTap::setEnabled(bool en)
  266. {
  267. _enabled = en;
  268. }
  269. bool MacEthernetTap::enabled() const
  270. {
  271. return _enabled;
  272. }
  273. bool MacEthernetTap::addIp(const InetAddress& ip)
  274. {
  275. char tmp[128];
  276. if (! ip)
  277. return false;
  278. std::string cmd;
  279. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  280. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  281. cmd.push_back(0);
  282. cmd.append(ip.toString(tmp));
  283. cmd.push_back(0);
  284. cmd.append("alias");
  285. cmd.push_back(0);
  286. uint16_t l = (uint16_t)cmd.length();
  287. _putLock.lock();
  288. write(_agentStdin, &l, 2);
  289. write(_agentStdin, cmd.data(), cmd.length());
  290. _putLock.unlock();
  291. return true;
  292. }
  293. bool MacEthernetTap::removeIp(const InetAddress& ip)
  294. {
  295. char tmp[128];
  296. if (! ip)
  297. return false;
  298. std::string cmd;
  299. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  300. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  301. cmd.push_back(0);
  302. cmd.append(ip.toString(tmp));
  303. cmd.push_back(0);
  304. cmd.append("-alias");
  305. cmd.push_back(0);
  306. uint16_t l = (uint16_t)cmd.length();
  307. _putLock.lock();
  308. write(_agentStdin, &l, 2);
  309. write(_agentStdin, cmd.data(), cmd.length());
  310. _putLock.unlock();
  311. return true;
  312. }
  313. std::vector<InetAddress> MacEthernetTap::ips() const
  314. {
  315. uint64_t now = OSUtils::now();
  316. if ((now - _lastIfAddrsUpdate) <= GETIFADDRS_CACHE_TIME) {
  317. return _ifaddrs;
  318. }
  319. _lastIfAddrsUpdate = now;
  320. struct ifaddrs* ifa = (struct ifaddrs*)0;
  321. std::vector<InetAddress> r;
  322. if (! getifaddrs(&ifa)) {
  323. struct ifaddrs* p = ifa;
  324. while (p) {
  325. if ((p->ifa_name) && (! strcmp(p->ifa_name, _dev.c_str())) && (p->ifa_addr)) {
  326. switch (p->ifa_addr->sa_family) {
  327. case AF_INET: {
  328. struct sockaddr_in* sin = (struct sockaddr_in*)p->ifa_addr;
  329. struct sockaddr_in* nm = (struct sockaddr_in*)p->ifa_netmask;
  330. r.push_back(InetAddress(&(sin->sin_addr.s_addr), 4, Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  331. } break;
  332. case AF_INET6: {
  333. struct sockaddr_in6* sin = (struct sockaddr_in6*)p->ifa_addr;
  334. struct sockaddr_in6* nm = (struct sockaddr_in6*)p->ifa_netmask;
  335. uint32_t b[4];
  336. memcpy(b, nm->sin6_addr.s6_addr, sizeof(b));
  337. 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])));
  338. } break;
  339. }
  340. }
  341. p = p->ifa_next;
  342. }
  343. freeifaddrs(ifa);
  344. }
  345. std::sort(r.begin(), r.end());
  346. r.erase(std::unique(r.begin(), r.end()), r.end());
  347. _ifaddrs = r;
  348. return r;
  349. }
  350. void MacEthernetTap::put(const MAC& from, const MAC& to, unsigned int etherType, const void* data, unsigned int len)
  351. {
  352. struct iovec iov[3];
  353. unsigned char hdr[15];
  354. uint16_t l;
  355. if ((_agentStdin > 0) && (len <= _mtu) && (_enabled)) {
  356. hdr[0] = ZT_MACETHERNETTAPAGENT_STDIN_CMD_PACKET;
  357. to.copyTo(hdr + 1, 6);
  358. from.copyTo(hdr + 7, 6);
  359. hdr[13] = (unsigned char)((etherType >> 8) & 0xff);
  360. hdr[14] = (unsigned char)(etherType & 0xff);
  361. l = (uint16_t)(len + 15);
  362. iov[0].iov_base = &l;
  363. iov[0].iov_len = 2;
  364. iov[1].iov_base = hdr;
  365. iov[1].iov_len = 15;
  366. iov[2].iov_base = const_cast<void*>(data);
  367. iov[2].iov_len = len;
  368. _putLock.lock();
  369. writev(_agentStdin, iov, 3);
  370. _putLock.unlock();
  371. }
  372. }
  373. std::string MacEthernetTap::deviceName() const
  374. {
  375. return _dev;
  376. }
  377. void MacEthernetTap::setFriendlyName(const char* friendlyName)
  378. {
  379. }
  380. void MacEthernetTap::scanMulticastGroups(std::vector<MulticastGroup>& added, std::vector<MulticastGroup>& removed)
  381. {
  382. std::vector<MulticastGroup> newGroups;
  383. struct ifmaddrs* ifmap = (struct ifmaddrs*)0;
  384. if (! getifmaddrs(&ifmap)) {
  385. struct ifmaddrs* p = ifmap;
  386. while (p) {
  387. if (p->ifma_addr->sa_family == AF_LINK) {
  388. struct sockaddr_dl* in = (struct sockaddr_dl*)p->ifma_name;
  389. struct sockaddr_dl* la = (struct sockaddr_dl*)p->ifma_addr;
  390. if ((la->sdl_alen == 6) && (in->sdl_nlen <= _dev.length()) && (! memcmp(_dev.data(), in->sdl_data, in->sdl_nlen)))
  391. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen, 6), 0));
  392. }
  393. p = p->ifma_next;
  394. }
  395. freeifmaddrs(ifmap);
  396. }
  397. std::vector<InetAddress> allIps(ips());
  398. for (std::vector<InetAddress>::iterator ip(allIps.begin()); ip != allIps.end(); ++ip)
  399. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  400. std::sort(newGroups.begin(), newGroups.end());
  401. newGroups.erase(std::unique(newGroups.begin(), newGroups.end()), newGroups.end());
  402. for (std::vector<MulticastGroup>::iterator m(newGroups.begin()); m != newGroups.end(); ++m) {
  403. if (! std::binary_search(_multicastGroups.begin(), _multicastGroups.end(), *m))
  404. added.push_back(*m);
  405. }
  406. for (std::vector<MulticastGroup>::iterator m(_multicastGroups.begin()); m != _multicastGroups.end(); ++m) {
  407. if (! std::binary_search(newGroups.begin(), newGroups.end(), *m))
  408. removed.push_back(*m);
  409. }
  410. _multicastGroups.swap(newGroups);
  411. }
  412. void MacEthernetTap::setMtu(unsigned int mtu)
  413. {
  414. if (_mtu != mtu) {
  415. char tmp[16];
  416. std::string cmd;
  417. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  418. cmd.append("mtu");
  419. cmd.push_back(0);
  420. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%u", mtu);
  421. cmd.append(tmp);
  422. cmd.push_back(0);
  423. uint16_t l = (uint16_t)cmd.length();
  424. _putLock.lock();
  425. write(_agentStdin, &l, 2);
  426. write(_agentStdin, cmd.data(), cmd.length());
  427. _putLock.unlock();
  428. _mtu = mtu;
  429. }
  430. }
  431. #define ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE 131072
  432. void MacEthernetTap::threadMain() throw()
  433. {
  434. char agentReadBuf[ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE];
  435. char agentStderrBuf[256];
  436. fd_set readfds, nullfds;
  437. MAC to, from;
  438. Thread::sleep(250);
  439. const int nfds = std::max(std::max(_shutdownSignalPipe[0], _agentStdout), _agentStderr) + 1;
  440. long agentReadPtr = 0;
  441. fcntl(_agentStdout, F_SETFL, fcntl(_agentStdout, F_GETFL) | O_NONBLOCK);
  442. fcntl(_agentStderr, F_SETFL, fcntl(_agentStderr, F_GETFL) | O_NONBLOCK);
  443. FD_ZERO(&readfds);
  444. FD_ZERO(&nullfds);
  445. for (;;) {
  446. FD_SET(_shutdownSignalPipe[0], &readfds);
  447. FD_SET(_agentStdout, &readfds);
  448. FD_SET(_agentStderr, &readfds);
  449. select(nfds, &readfds, &nullfds, &nullfds, (struct timeval*)0);
  450. if (FD_ISSET(_shutdownSignalPipe[0], &readfds))
  451. break;
  452. if (FD_ISSET(_agentStdout, &readfds)) {
  453. long n = (long)read(_agentStdout, agentReadBuf + agentReadPtr, ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE - agentReadPtr);
  454. if (n > 0) {
  455. agentReadPtr += n;
  456. while (agentReadPtr >= 2) {
  457. long len = *((uint16_t*)agentReadBuf);
  458. if (agentReadPtr >= (len + 2)) {
  459. char* msg = agentReadBuf + 2;
  460. if ((len > 14) && (_enabled)) {
  461. to.setTo(msg, 6);
  462. from.setTo(msg + 6, 6);
  463. _handler(_arg, (void*)0, _nwid, from, to, ntohs(((const uint16_t*)msg)[6]), 0, (const void*)(msg + 14), (unsigned int)len - 14);
  464. }
  465. if (agentReadPtr > (len + 2)) {
  466. memmove(agentReadBuf, agentReadBuf + len + 2, agentReadPtr -= (len + 2));
  467. }
  468. else {
  469. agentReadPtr = 0;
  470. }
  471. }
  472. else {
  473. break;
  474. }
  475. }
  476. }
  477. }
  478. if (FD_ISSET(_agentStderr, &readfds)) {
  479. read(_agentStderr, agentStderrBuf, sizeof(agentStderrBuf));
  480. /*
  481. const ssize_t n = read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  482. if (n > 0)
  483. write(STDERR_FILENO,agentStderrBuf,(size_t)n);
  484. */
  485. }
  486. }
  487. ::close(_agentStdin);
  488. ::close(_agentStdout);
  489. ::close(_agentStderr);
  490. ::close(_agentStdin2);
  491. ::close(_agentStdout2);
  492. ::close(_agentStderr2);
  493. ::close(_shutdownSignalPipe[0]);
  494. ::close(_shutdownSignalPipe[1]);
  495. }
  496. void MacEthernetTap::setDns(const char* domain, const std::vector<InetAddress>& servers)
  497. {
  498. MacDNSHelper::setDNS(this->_nwid, domain, servers);
  499. }
  500. } // namespace ZeroTier
  501. #endif // __APPLE__