MacEthernetTap.cpp 15 KB

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