MacEthernetTap.cpp 15 KB

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