MacEthernetTap.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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: 2025-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::removeIps(_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 = vfork();
  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 = vfork();
  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) { _enabled = en; }
  261. bool MacEthernetTap::enabled() const { return _enabled; }
  262. bool MacEthernetTap::addIp(const InetAddress &ip)
  263. {
  264. char tmp[128];
  265. if (!ip)
  266. return false;
  267. std::string cmd;
  268. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  269. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  270. cmd.push_back(0);
  271. cmd.append(ip.toString(tmp));
  272. cmd.push_back(0);
  273. cmd.append("alias");
  274. cmd.push_back(0);
  275. uint16_t l = (uint16_t)cmd.length();
  276. _putLock.lock();
  277. write(_agentStdin,&l,2);
  278. write(_agentStdin,cmd.data(),cmd.length());
  279. _putLock.unlock();
  280. return true;
  281. }
  282. bool MacEthernetTap::removeIp(const InetAddress &ip)
  283. {
  284. char tmp[128];
  285. if (!ip)
  286. return false;
  287. std::string cmd;
  288. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  289. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  290. cmd.push_back(0);
  291. cmd.append(ip.toString(tmp));
  292. cmd.push_back(0);
  293. cmd.append("-alias");
  294. cmd.push_back(0);
  295. uint16_t l = (uint16_t)cmd.length();
  296. _putLock.lock();
  297. write(_agentStdin,&l,2);
  298. write(_agentStdin,cmd.data(),cmd.length());
  299. _putLock.unlock();
  300. return true;
  301. }
  302. std::vector<InetAddress> MacEthernetTap::ips() const
  303. {
  304. uint64_t now = OSUtils::now();
  305. if ((now - _lastIfAddrsUpdate) <= GETIFADDRS_CACHE_TIME) {
  306. return _ifaddrs;
  307. }
  308. _lastIfAddrsUpdate = now;
  309. struct ifaddrs *ifa = (struct ifaddrs *)0;
  310. std::vector<InetAddress> r;
  311. if (!getifaddrs(&ifa)) {
  312. struct ifaddrs *p = ifa;
  313. while (p) {
  314. if ((p->ifa_name)&&(!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)) {
  315. switch(p->ifa_addr->sa_family) {
  316. case AF_INET: {
  317. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  318. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  319. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  320. } break;
  321. case AF_INET6: {
  322. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  323. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  324. uint32_t b[4];
  325. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  326. 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])));
  327. } break;
  328. }
  329. }
  330. p = p->ifa_next;
  331. }
  332. freeifaddrs(ifa);
  333. }
  334. std::sort(r.begin(),r.end());
  335. r.erase(std::unique(r.begin(),r.end()),r.end());
  336. _ifaddrs = r;
  337. return r;
  338. }
  339. void MacEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  340. {
  341. struct iovec iov[3];
  342. unsigned char hdr[15];
  343. uint16_t l;
  344. if ((_agentStdin > 0)&&(len <= _mtu)&&(_enabled)) {
  345. hdr[0] = ZT_MACETHERNETTAPAGENT_STDIN_CMD_PACKET;
  346. to.copyTo(hdr + 1,6);
  347. from.copyTo(hdr + 7,6);
  348. hdr[13] = (unsigned char)((etherType >> 8) & 0xff);
  349. hdr[14] = (unsigned char)(etherType & 0xff);
  350. l = (uint16_t)(len + 15);
  351. iov[0].iov_base = &l;
  352. iov[0].iov_len = 2;
  353. iov[1].iov_base = hdr;
  354. iov[1].iov_len = 15;
  355. iov[2].iov_base = const_cast<void *>(data);
  356. iov[2].iov_len = len;
  357. _putLock.lock();
  358. writev(_agentStdin,iov,3);
  359. _putLock.unlock();
  360. }
  361. }
  362. std::string MacEthernetTap::deviceName() const { return _dev; }
  363. void MacEthernetTap::setFriendlyName(const char *friendlyName) {}
  364. void MacEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  365. {
  366. std::vector<MulticastGroup> newGroups;
  367. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  368. if (!getifmaddrs(&ifmap)) {
  369. struct ifmaddrs *p = ifmap;
  370. while (p) {
  371. if (p->ifma_addr->sa_family == AF_LINK) {
  372. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  373. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  374. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  375. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  376. }
  377. p = p->ifma_next;
  378. }
  379. freeifmaddrs(ifmap);
  380. }
  381. std::vector<InetAddress> allIps(ips());
  382. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  383. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  384. std::sort(newGroups.begin(),newGroups.end());
  385. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  386. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  387. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  388. added.push_back(*m);
  389. }
  390. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  391. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  392. removed.push_back(*m);
  393. }
  394. _multicastGroups.swap(newGroups);
  395. }
  396. void MacEthernetTap::setMtu(unsigned int mtu)
  397. {
  398. if (_mtu != mtu) {
  399. char tmp[16];
  400. std::string cmd;
  401. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  402. cmd.append("mtu");
  403. cmd.push_back(0);
  404. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%u",mtu);
  405. cmd.append(tmp);
  406. cmd.push_back(0);
  407. uint16_t l = (uint16_t)cmd.length();
  408. _putLock.lock();
  409. write(_agentStdin,&l,2);
  410. write(_agentStdin,cmd.data(),cmd.length());
  411. _putLock.unlock();
  412. _mtu = mtu;
  413. }
  414. }
  415. #define ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE 131072
  416. void MacEthernetTap::threadMain()
  417. throw()
  418. {
  419. char agentReadBuf[ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE];
  420. char agentStderrBuf[256];
  421. fd_set readfds,nullfds;
  422. MAC to,from;
  423. Thread::sleep(250);
  424. const int nfds = std::max(std::max(_shutdownSignalPipe[0],_agentStdout),_agentStderr) + 1;
  425. long agentReadPtr = 0;
  426. fcntl(_agentStdout,F_SETFL,fcntl(_agentStdout,F_GETFL)|O_NONBLOCK);
  427. fcntl(_agentStderr,F_SETFL,fcntl(_agentStderr,F_GETFL)|O_NONBLOCK);
  428. FD_ZERO(&readfds);
  429. FD_ZERO(&nullfds);
  430. for(;;) {
  431. FD_SET(_shutdownSignalPipe[0],&readfds);
  432. FD_SET(_agentStdout,&readfds);
  433. FD_SET(_agentStderr,&readfds);
  434. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  435. if (FD_ISSET(_shutdownSignalPipe[0],&readfds))
  436. break;
  437. if (FD_ISSET(_agentStdout,&readfds)) {
  438. long n = (long)read(_agentStdout,agentReadBuf + agentReadPtr,ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE - agentReadPtr);
  439. if (n > 0) {
  440. agentReadPtr += n;
  441. while (agentReadPtr >= 2) {
  442. long len = *((uint16_t *)agentReadBuf);
  443. if (agentReadPtr >= (len + 2)) {
  444. char *msg = agentReadBuf + 2;
  445. if ((len > 14)&&(_enabled)) {
  446. to.setTo(msg,6);
  447. from.setTo(msg + 6,6);
  448. _handler(_arg,(void *)0,_nwid,from,to,ntohs(((const uint16_t *)msg)[6]),0,(const void *)(msg + 14),(unsigned int)len - 14);
  449. }
  450. if (agentReadPtr > (len + 2)) {
  451. memmove(agentReadBuf,agentReadBuf + len + 2,agentReadPtr -= (len + 2));
  452. } else {
  453. agentReadPtr = 0;
  454. }
  455. } else {
  456. break;
  457. }
  458. }
  459. }
  460. }
  461. if (FD_ISSET(_agentStderr,&readfds)) {
  462. read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  463. /*
  464. const ssize_t n = read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  465. if (n > 0)
  466. write(STDERR_FILENO,agentStderrBuf,(size_t)n);
  467. */
  468. }
  469. }
  470. ::close(_agentStdin);
  471. ::close(_agentStdout);
  472. ::close(_agentStderr);
  473. ::close(_agentStdin2);
  474. ::close(_agentStdout2);
  475. ::close(_agentStderr2);
  476. ::close(_shutdownSignalPipe[0]);
  477. ::close(_shutdownSignalPipe[1]);
  478. }
  479. void MacEthernetTap::setDns(const char *domain, const std::vector<InetAddress> &servers)
  480. {
  481. MacDNSHelper::setDNS(this->_nwid, domain, servers);
  482. }
  483. } // namespace ZeroTier
  484. #endif // __APPLE__