MacEthernetTap.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. {
  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. } else if (pid > 0) {
  123. int rv = 0;
  124. waitpid(pid,&rv,0);
  125. }
  126. }
  127. p = p->ifa_next;
  128. }
  129. freeifaddrs(ifa);
  130. }
  131. }
  132. unsigned int devNo = 100 + ((nwid ^ (nwid >> 32) ^ (nwid >> 48)) % 4900);
  133. for(;;) {
  134. OSUtils::ztsnprintf(devnostr,sizeof(devnostr),"%u",devNo);
  135. OSUtils::ztsnprintf(devstr,sizeof(devstr),"feth%u",devNo);
  136. bool duplicate = false;
  137. struct ifaddrs *ifa = (struct ifaddrs *)0;
  138. if (!getifaddrs(&ifa)) {
  139. struct ifaddrs *p = ifa;
  140. while (p) {
  141. if (!strcmp(p->ifa_name,devstr)) {
  142. duplicate = true;
  143. break;
  144. }
  145. p = p->ifa_next;
  146. }
  147. freeifaddrs(ifa);
  148. }
  149. if (duplicate) {
  150. devNo = (devNo + 1) % 5000;
  151. if (devNo < 100)
  152. devNo = 100;
  153. } else {
  154. _dev = devstr;
  155. _devNo = devNo;
  156. break;
  157. }
  158. }
  159. if (::pipe(_shutdownSignalPipe))
  160. throw std::runtime_error("pipe creation failed");
  161. int agentStdin[2];
  162. int agentStdout[2];
  163. int agentStderr[2];
  164. if (::pipe(agentStdin))
  165. throw std::runtime_error("pipe creation failed");
  166. if (::pipe(agentStdout))
  167. throw std::runtime_error("pipe creation failed");
  168. if (::pipe(agentStderr))
  169. throw std::runtime_error("pipe creation failed");
  170. _agentStdin = agentStdin[1];
  171. _agentStdout = agentStdout[0];
  172. _agentStderr = agentStderr[0];
  173. _agentStdin2 = agentStdin[0];
  174. _agentStdout2 = agentStdout[1];
  175. _agentStderr2 = agentStderr[1];
  176. long apid = (long)fork();
  177. if (apid < 0) {
  178. throw std::runtime_error("fork failed");
  179. } else if (apid == 0) {
  180. ::dup2(agentStdin[0],STDIN_FILENO);
  181. ::dup2(agentStdout[1],STDOUT_FILENO);
  182. ::dup2(agentStderr[1],STDERR_FILENO);
  183. ::close(agentStdin[0]);
  184. ::close(agentStdin[1]);
  185. ::close(agentStdout[0]);
  186. ::close(agentStdout[1]);
  187. ::close(agentStderr[0]);
  188. ::close(agentStderr[1]);
  189. ::execl(agentPath.c_str(),agentPath.c_str(),devnostr,ethaddr,mtustr,metricstr,(char *)0);
  190. ::_exit(-1);
  191. } else {
  192. _agentPid = apid;
  193. // Wait up to 10 seconds for the subprocess to actually create the device. This prevents
  194. // things like routes from being created before the device exists.
  195. for(int waitLoops=0;;++waitLoops) {
  196. struct ifaddrs *ifa = (struct ifaddrs *)0;
  197. if (!getifaddrs(&ifa)) {
  198. struct ifaddrs *p = ifa;
  199. while (p) {
  200. if ((p->ifa_name)&&(!strcmp(devstr, p->ifa_name))) {
  201. waitLoops = -1;
  202. break;
  203. }
  204. p = p->ifa_next;
  205. }
  206. freeifaddrs(ifa);
  207. }
  208. if (waitLoops == -1) {
  209. break;
  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::removeIps(_nwid);
  225. Mutex::Lock _gl(globalTapCreateLock);
  226. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  227. int ec = 0;
  228. ::kill(_agentPid,SIGKILL);
  229. ::waitpid(_agentPid,&ec,0);
  230. args[0] = "/sbin/ifconfig";
  231. args[1] = _dev.c_str();
  232. args[2] = "destroy";
  233. args[3] = (char *)0;
  234. pid0 = vfork();
  235. if (pid0 == 0) {
  236. execv(args[0],const_cast<char **>(args));
  237. _exit(-1);
  238. }
  239. snprintf(tmp,sizeof(tmp),"feth%u",_devNo + 5000);
  240. //args[0] = "/sbin/ifconfig";
  241. args[1] = tmp;
  242. //args[2] = "destroy";
  243. //args[3] = (char *)0;
  244. pid1 = vfork();
  245. if (pid1 == 0) {
  246. execv(args[0],const_cast<char **>(args));
  247. _exit(-1);
  248. }
  249. if (pid0 > 0) {
  250. int rv = 0;
  251. waitpid(pid0,&rv,0);
  252. }
  253. if (pid1 > 0) {
  254. int rv = 0;
  255. waitpid(pid1,&rv,0);
  256. }
  257. Thread::join(_thread);
  258. }
  259. void MacEthernetTap::setEnabled(bool en) { _enabled = en; }
  260. bool MacEthernetTap::enabled() const { return _enabled; }
  261. bool MacEthernetTap::addIp(const InetAddress &ip)
  262. {
  263. char tmp[128];
  264. if (!ip)
  265. return false;
  266. std::string cmd;
  267. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  268. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  269. cmd.push_back(0);
  270. cmd.append(ip.toString(tmp));
  271. cmd.push_back(0);
  272. cmd.append("alias");
  273. cmd.push_back(0);
  274. uint16_t l = (uint16_t)cmd.length();
  275. _putLock.lock();
  276. write(_agentStdin,&l,2);
  277. write(_agentStdin,cmd.data(),cmd.length());
  278. _putLock.unlock();
  279. return true;
  280. }
  281. bool MacEthernetTap::removeIp(const InetAddress &ip)
  282. {
  283. char tmp[128];
  284. if (!ip)
  285. return false;
  286. std::string cmd;
  287. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  288. cmd.append((ip.ss_family == AF_INET6) ? "inet6" : "inet");
  289. cmd.push_back(0);
  290. cmd.append(ip.toString(tmp));
  291. cmd.push_back(0);
  292. cmd.append("-alias");
  293. cmd.push_back(0);
  294. uint16_t l = (uint16_t)cmd.length();
  295. _putLock.lock();
  296. write(_agentStdin,&l,2);
  297. write(_agentStdin,cmd.data(),cmd.length());
  298. _putLock.unlock();
  299. return true;
  300. }
  301. std::vector<InetAddress> MacEthernetTap::ips() const
  302. {
  303. struct ifaddrs *ifa = (struct ifaddrs *)0;
  304. std::vector<InetAddress> r;
  305. if (!getifaddrs(&ifa)) {
  306. struct ifaddrs *p = ifa;
  307. while (p) {
  308. if ((p->ifa_name)&&(!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)) {
  309. switch(p->ifa_addr->sa_family) {
  310. case AF_INET: {
  311. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  312. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  313. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  314. } break;
  315. case AF_INET6: {
  316. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  317. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  318. uint32_t b[4];
  319. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  320. 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])));
  321. } break;
  322. }
  323. }
  324. p = p->ifa_next;
  325. }
  326. freeifaddrs(ifa);
  327. }
  328. std::sort(r.begin(),r.end());
  329. r.erase(std::unique(r.begin(),r.end()),r.end());
  330. return r;
  331. }
  332. void MacEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  333. {
  334. struct iovec iov[3];
  335. unsigned char hdr[15];
  336. uint16_t l;
  337. if ((_agentStdin > 0)&&(len <= _mtu)&&(_enabled)) {
  338. hdr[0] = ZT_MACETHERNETTAPAGENT_STDIN_CMD_PACKET;
  339. to.copyTo(hdr + 1,6);
  340. from.copyTo(hdr + 7,6);
  341. hdr[13] = (unsigned char)((etherType >> 8) & 0xff);
  342. hdr[14] = (unsigned char)(etherType & 0xff);
  343. l = (uint16_t)(len + 15);
  344. iov[0].iov_base = &l;
  345. iov[0].iov_len = 2;
  346. iov[1].iov_base = hdr;
  347. iov[1].iov_len = 15;
  348. iov[2].iov_base = const_cast<void *>(data);
  349. iov[2].iov_len = len;
  350. _putLock.lock();
  351. writev(_agentStdin,iov,3);
  352. _putLock.unlock();
  353. }
  354. }
  355. std::string MacEthernetTap::deviceName() const { return _dev; }
  356. void MacEthernetTap::setFriendlyName(const char *friendlyName) {}
  357. void MacEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  358. {
  359. std::vector<MulticastGroup> newGroups;
  360. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  361. if (!getifmaddrs(&ifmap)) {
  362. struct ifmaddrs *p = ifmap;
  363. while (p) {
  364. if (p->ifma_addr->sa_family == AF_LINK) {
  365. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  366. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  367. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  368. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  369. }
  370. p = p->ifma_next;
  371. }
  372. freeifmaddrs(ifmap);
  373. }
  374. std::vector<InetAddress> allIps(ips());
  375. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  376. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  377. std::sort(newGroups.begin(),newGroups.end());
  378. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  379. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  380. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  381. added.push_back(*m);
  382. }
  383. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  384. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  385. removed.push_back(*m);
  386. }
  387. _multicastGroups.swap(newGroups);
  388. }
  389. void MacEthernetTap::setMtu(unsigned int mtu)
  390. {
  391. if (_mtu != mtu) {
  392. char tmp[16];
  393. std::string cmd;
  394. cmd.push_back((char)ZT_MACETHERNETTAPAGENT_STDIN_CMD_IFCONFIG);
  395. cmd.append("mtu");
  396. cmd.push_back(0);
  397. OSUtils::ztsnprintf(tmp,sizeof(tmp),"%u",mtu);
  398. cmd.append(tmp);
  399. cmd.push_back(0);
  400. uint16_t l = (uint16_t)cmd.length();
  401. _putLock.lock();
  402. write(_agentStdin,&l,2);
  403. write(_agentStdin,cmd.data(),cmd.length());
  404. _putLock.unlock();
  405. _mtu = mtu;
  406. }
  407. }
  408. #define ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE 131072
  409. void MacEthernetTap::threadMain()
  410. throw()
  411. {
  412. char agentReadBuf[ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE];
  413. char agentStderrBuf[256];
  414. fd_set readfds,nullfds;
  415. MAC to,from;
  416. Thread::sleep(250);
  417. const int nfds = std::max(std::max(_shutdownSignalPipe[0],_agentStdout),_agentStderr) + 1;
  418. long agentReadPtr = 0;
  419. fcntl(_agentStdout,F_SETFL,fcntl(_agentStdout,F_GETFL)|O_NONBLOCK);
  420. fcntl(_agentStderr,F_SETFL,fcntl(_agentStderr,F_GETFL)|O_NONBLOCK);
  421. FD_ZERO(&readfds);
  422. FD_ZERO(&nullfds);
  423. for(;;) {
  424. FD_SET(_shutdownSignalPipe[0],&readfds);
  425. FD_SET(_agentStdout,&readfds);
  426. FD_SET(_agentStderr,&readfds);
  427. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  428. if (FD_ISSET(_shutdownSignalPipe[0],&readfds))
  429. break;
  430. if (FD_ISSET(_agentStdout,&readfds)) {
  431. long n = (long)read(_agentStdout,agentReadBuf + agentReadPtr,ZT_MACETHERNETTAP_AGENT_READ_BUF_SIZE - agentReadPtr);
  432. if (n > 0) {
  433. agentReadPtr += n;
  434. while (agentReadPtr >= 2) {
  435. long len = *((uint16_t *)agentReadBuf);
  436. if (agentReadPtr >= (len + 2)) {
  437. char *msg = agentReadBuf + 2;
  438. if ((len > 14)&&(_enabled)) {
  439. to.setTo(msg,6);
  440. from.setTo(msg + 6,6);
  441. _handler(_arg,(void *)0,_nwid,from,to,ntohs(((const uint16_t *)msg)[6]),0,(const void *)(msg + 14),(unsigned int)len - 14);
  442. }
  443. if (agentReadPtr > (len + 2)) {
  444. memmove(agentReadBuf,agentReadBuf + len + 2,agentReadPtr -= (len + 2));
  445. } else {
  446. agentReadPtr = 0;
  447. }
  448. } else {
  449. break;
  450. }
  451. }
  452. }
  453. }
  454. if (FD_ISSET(_agentStderr,&readfds)) {
  455. read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  456. /*
  457. const ssize_t n = read(_agentStderr,agentStderrBuf,sizeof(agentStderrBuf));
  458. if (n > 0)
  459. write(STDERR_FILENO,agentStderrBuf,(size_t)n);
  460. */
  461. }
  462. }
  463. ::close(_agentStdin);
  464. ::close(_agentStdout);
  465. ::close(_agentStderr);
  466. ::close(_agentStdin2);
  467. ::close(_agentStdout2);
  468. ::close(_agentStderr2);
  469. ::close(_shutdownSignalPipe[0]);
  470. ::close(_shutdownSignalPipe[1]);
  471. }
  472. void MacEthernetTap::setDns(const char *domain, const std::vector<InetAddress> &servers)
  473. {
  474. MacDNSHelper::setDNS(this->_nwid, domain, servers);
  475. }
  476. } // namespace ZeroTier
  477. #endif // __APPLE__