MacKextEthernetTap.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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 "MacDNSHelper.hpp"
  14. #include <arpa/inet.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <net/if.h>
  18. #include <net/if_arp.h>
  19. #include <net/if_dl.h>
  20. #include <net/if_media.h>
  21. #include <net/route.h>
  22. #include <netinet/icmp6.h>
  23. #include <netinet/in.h>
  24. #include <netinet/in_var.h>
  25. #include <netinet6/in6_var.h>
  26. #include <signal.h>
  27. #include <stdint.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <sys/cdefs.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/param.h>
  34. #include <sys/select.h>
  35. #include <sys/socket.h>
  36. #include <sys/stat.h>
  37. #include <sys/sysctl.h>
  38. #include <sys/types.h>
  39. #include <sys/uio.h>
  40. #include <sys/wait.h>
  41. #include <unistd.h>
  42. // OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
  43. struct prf_ra {
  44. u_char onlink : 1;
  45. u_char autonomous : 1;
  46. u_char reserved : 6;
  47. } prf_ra;
  48. #include <ifaddrs.h>
  49. #include <netinet6/nd6.h>
  50. // These are KERNEL_PRIVATE... why?
  51. #ifndef SIOCAUTOCONF_START
  52. #define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
  53. #endif
  54. #ifndef SIOCAUTOCONF_STOP
  55. #define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
  56. #endif
  57. // --------------------------------------------------------------------------
  58. // --------------------------------------------------------------------------
  59. // This source is from:
  60. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  61. // It's here because OSX 10.6 does not have this convenience function.
  62. #define SALIGN (sizeof(uint32_t) - 1)
  63. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : (SALIGN + 1))
  64. #define MAX_SYSCTL_TRY 5
  65. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  66. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  67. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  68. // #define DARWIN_COMPAT
  69. // #ifdef DARWIN_COMPAT
  70. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  71. #define GIM_RTM_ADDR RTM_NEWMADDR2
  72. // #else
  73. // #define GIM_SYSCTL_MIB NET_RT_IFMALIST
  74. // #define GIM_RTM_ADDR RTM_NEWMADDR
  75. // #endif
  76. // Not in 10.6 includes so use our own
  77. struct _intl_ifmaddrs {
  78. struct _intl_ifmaddrs* ifma_next;
  79. struct sockaddr* ifma_name;
  80. struct sockaddr* ifma_addr;
  81. struct sockaddr* ifma_lladdr;
  82. };
  83. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs** pif)
  84. {
  85. int icnt = 1;
  86. int dcnt = 0;
  87. int ntry = 0;
  88. size_t len;
  89. size_t needed;
  90. int mib[6];
  91. int i;
  92. char* buf;
  93. char* data;
  94. char* next;
  95. char* p;
  96. struct ifma_msghdr2* ifmam;
  97. struct _intl_ifmaddrs *ifa, *ift;
  98. struct rt_msghdr* rtm;
  99. struct sockaddr* sa;
  100. mib[0] = CTL_NET;
  101. mib[1] = PF_ROUTE;
  102. mib[2] = 0; /* protocol */
  103. mib[3] = 0; /* wildcard address family */
  104. mib[4] = GIM_SYSCTL_MIB;
  105. mib[5] = 0; /* no flags */
  106. do {
  107. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  108. return (-1);
  109. if ((buf = (char*)malloc(needed)) == NULL)
  110. return (-1);
  111. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  112. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  113. free(buf);
  114. return (-1);
  115. }
  116. free(buf);
  117. buf = NULL;
  118. }
  119. } while (buf == NULL);
  120. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  121. rtm = (struct rt_msghdr*)(void*)next;
  122. if (rtm->rtm_version != RTM_VERSION)
  123. continue;
  124. switch (rtm->rtm_type) {
  125. case GIM_RTM_ADDR:
  126. ifmam = (struct ifma_msghdr2*)(void*)rtm;
  127. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  128. break;
  129. icnt++;
  130. p = (char*)(ifmam + 1);
  131. for (i = 0; i < RTAX_MAX; i++) {
  132. if ((RTA_MASKS & ifmam->ifmam_addrs & (1 << i)) == 0)
  133. continue;
  134. sa = (struct sockaddr*)(void*)p;
  135. len = SA_RLEN(sa);
  136. dcnt += len;
  137. p += len;
  138. }
  139. break;
  140. }
  141. }
  142. data = (char*)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  143. if (data == NULL) {
  144. free(buf);
  145. return (-1);
  146. }
  147. ifa = (struct _intl_ifmaddrs*)(void*)data;
  148. data += sizeof(struct _intl_ifmaddrs) * icnt;
  149. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  150. ift = ifa;
  151. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  152. rtm = (struct rt_msghdr*)(void*)next;
  153. if (rtm->rtm_version != RTM_VERSION)
  154. continue;
  155. switch (rtm->rtm_type) {
  156. case GIM_RTM_ADDR:
  157. ifmam = (struct ifma_msghdr2*)(void*)rtm;
  158. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  159. break;
  160. p = (char*)(ifmam + 1);
  161. for (i = 0; i < RTAX_MAX; i++) {
  162. if ((RTA_MASKS & ifmam->ifmam_addrs & (1 << i)) == 0)
  163. continue;
  164. sa = (struct sockaddr*)(void*)p;
  165. len = SA_RLEN(sa);
  166. switch (i) {
  167. case RTAX_GATEWAY:
  168. ift->ifma_lladdr = (struct sockaddr*)(void*)data;
  169. memcpy(data, p, len);
  170. data += len;
  171. break;
  172. case RTAX_IFP:
  173. ift->ifma_name = (struct sockaddr*)(void*)data;
  174. memcpy(data, p, len);
  175. data += len;
  176. break;
  177. case RTAX_IFA:
  178. ift->ifma_addr = (struct sockaddr*)(void*)data;
  179. memcpy(data, p, len);
  180. data += len;
  181. break;
  182. default:
  183. data += len;
  184. break;
  185. }
  186. p += len;
  187. }
  188. ift->ifma_next = ift + 1;
  189. ift = ift->ifma_next;
  190. break;
  191. }
  192. }
  193. free(buf);
  194. if (ift > ifa) {
  195. ift--;
  196. ift->ifma_next = NULL;
  197. *pif = ifa;
  198. }
  199. else {
  200. *pif = NULL;
  201. free(ifa);
  202. }
  203. return (0);
  204. }
  205. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs* ifmp)
  206. {
  207. free(ifmp);
  208. }
  209. // --------------------------------------------------------------------------
  210. // --------------------------------------------------------------------------
  211. #include "../node/Constants.hpp"
  212. #include "../node/Dictionary.hpp"
  213. #include "../node/Mutex.hpp"
  214. #include "../node/Utils.hpp"
  215. #include "MacKextEthernetTap.hpp"
  216. #include "OSUtils.hpp"
  217. #include <algorithm>
  218. #include <map>
  219. #include <set>
  220. #include <string>
  221. // ff:ff:ff:ff:ff:ff with no ADI
  222. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff), 0);
  223. static inline bool _setIpv6Stuff(const char* ifname, bool performNUD, bool acceptRouterAdverts)
  224. {
  225. struct in6_ndireq nd;
  226. struct in6_ifreq ifr;
  227. int s = socket(AF_INET6, SOCK_DGRAM, 0);
  228. if (s <= 0)
  229. return false;
  230. memset(&nd, 0, sizeof(nd));
  231. strncpy(nd.ifname, ifname, sizeof(nd.ifname));
  232. if (ioctl(s, SIOCGIFINFO_IN6, &nd)) {
  233. close(s);
  234. return false;
  235. }
  236. unsigned long oldFlags = (unsigned long)nd.ndi.flags;
  237. if (performNUD)
  238. nd.ndi.flags |= ND6_IFF_PERFORMNUD;
  239. else
  240. nd.ndi.flags &= ~ND6_IFF_PERFORMNUD;
  241. if (oldFlags != (unsigned long)nd.ndi.flags) {
  242. if (ioctl(s, SIOCSIFINFO_FLAGS, &nd)) {
  243. close(s);
  244. return false;
  245. }
  246. }
  247. memset(&ifr, 0, sizeof(ifr));
  248. strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
  249. if (ioctl(s, acceptRouterAdverts ? SIOCAUTOCONF_START : SIOCAUTOCONF_STOP, &ifr)) {
  250. close(s);
  251. return false;
  252. }
  253. close(s);
  254. return true;
  255. }
  256. namespace ZeroTier {
  257. static long globalTapsRunning = 0;
  258. static Mutex globalTapCreateLock;
  259. MacKextEthernetTap::MacKextEthernetTap(
  260. const char* homePath,
  261. const MAC& mac,
  262. unsigned int mtu,
  263. unsigned int metric,
  264. uint64_t nwid,
  265. const char* friendlyName,
  266. void (*handler)(void*, void*, uint64_t, const MAC&, const MAC&, unsigned int, unsigned int, const void* data, unsigned int len),
  267. void* arg)
  268. : _handler(handler)
  269. , _arg(arg)
  270. , _nwid(nwid)
  271. , _homePath(homePath)
  272. , _mtu(mtu)
  273. , _metric(metric)
  274. , _fd(0)
  275. , _enabled(true)
  276. {
  277. char devpath[64], ethaddr[64], mtustr[32], metstr[32], nwids[32];
  278. struct stat stattmp;
  279. OSUtils::ztsnprintf(nwids, sizeof(nwids), "%.16llx", nwid);
  280. Mutex::Lock _gl(globalTapCreateLock);
  281. if (::stat("/dev/zt0", &stattmp)) {
  282. long kextpid = (long)fork();
  283. if (kextpid == 0) {
  284. ::chdir(homePath);
  285. OSUtils::redirectUnixOutputs("/dev/null", (const char*)0);
  286. ::execl("/sbin/kextload", "/sbin/kextload", "-q", "-repository", homePath, "tap.kext", (const char*)0);
  287. ::_exit(-1);
  288. }
  289. else if (kextpid > 0) {
  290. int exitcode = -1;
  291. ::waitpid(kextpid, &exitcode, 0);
  292. }
  293. ::usleep(500); // give tap device driver time to start up and try again
  294. if (::stat("/dev/zt0", &stattmp))
  295. throw std::runtime_error("/dev/zt# tap devices do not exist and cannot load tap.kext");
  296. }
  297. // Try to reopen the last device we had, if we had one and it's still unused.
  298. std::map<std::string, std::string> globalDeviceMap;
  299. FILE* devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(), "r");
  300. if (devmapf) {
  301. char buf[256];
  302. while (fgets(buf, sizeof(buf), devmapf)) {
  303. char* x = (char*)0;
  304. char* y = (char*)0;
  305. char* saveptr = (char*)0;
  306. for (char* f = Utils::stok(buf, "\r\n=", &saveptr); (f); f = Utils::stok((char*)0, "\r\n=", &saveptr)) {
  307. if (! x)
  308. x = f;
  309. else if (! y)
  310. y = f;
  311. else
  312. break;
  313. }
  314. if ((x) && (y) && (x[0]) && (y[0]))
  315. globalDeviceMap[x] = y;
  316. }
  317. fclose(devmapf);
  318. }
  319. bool recalledDevice = false;
  320. std::map<std::string, std::string>::const_iterator gdmEntry = globalDeviceMap.find(nwids);
  321. if (gdmEntry != globalDeviceMap.end()) {
  322. std::string devpath("/dev/");
  323. devpath.append(gdmEntry->second);
  324. if (stat(devpath.c_str(), &stattmp) == 0) {
  325. _fd = ::open(devpath.c_str(), O_RDWR);
  326. if (_fd > 0) {
  327. _dev = gdmEntry->second;
  328. recalledDevice = true;
  329. }
  330. }
  331. }
  332. // Open the first unused tap device if we didn't recall a previous one.
  333. if (! recalledDevice) {
  334. for (int i = 0; i < 64; ++i) {
  335. OSUtils::ztsnprintf(devpath, sizeof(devpath), "/dev/zt%d", i);
  336. if (stat(devpath, &stattmp))
  337. throw std::runtime_error("no more TAP devices available");
  338. _fd = ::open(devpath, O_RDWR);
  339. if (_fd > 0) {
  340. char foo[16];
  341. OSUtils::ztsnprintf(foo, sizeof(foo), "zt%d", i);
  342. _dev = foo;
  343. break;
  344. }
  345. }
  346. }
  347. if (_fd <= 0)
  348. throw std::runtime_error("unable to open TAP device or no more devices available");
  349. if (fcntl(_fd, F_SETFL, fcntl(_fd, F_GETFL) & ~O_NONBLOCK) == -1) {
  350. ::close(_fd);
  351. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  352. }
  353. // Configure MAC address and MTU, bring interface up
  354. 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]);
  355. OSUtils::ztsnprintf(mtustr, sizeof(mtustr), "%u", _mtu);
  356. OSUtils::ztsnprintf(metstr, sizeof(metstr), "%u", _metric);
  357. long cpid = (long)fork();
  358. if (cpid == 0) {
  359. ::execl("/sbin/ifconfig", "/sbin/ifconfig", _dev.c_str(), "lladdr", ethaddr, "mtu", mtustr, "metric", metstr, "up", (const char*)0);
  360. ::_exit(-1);
  361. }
  362. else if (cpid > 0) {
  363. int exitcode = -1;
  364. ::waitpid(cpid, &exitcode, 0);
  365. if (exitcode) {
  366. ::close(_fd);
  367. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  368. }
  369. }
  370. _setIpv6Stuff(_dev.c_str(), true, false);
  371. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  372. fcntl(_fd, F_SETFD, fcntl(_fd, F_GETFD) | FD_CLOEXEC);
  373. ::pipe(_shutdownSignalPipe);
  374. ++globalTapsRunning;
  375. globalDeviceMap[nwids] = _dev;
  376. devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(), "w");
  377. if (devmapf) {
  378. gdmEntry = globalDeviceMap.begin();
  379. while (gdmEntry != globalDeviceMap.end()) {
  380. fprintf(devmapf, "%s=%s\n", gdmEntry->first.c_str(), gdmEntry->second.c_str());
  381. ++gdmEntry;
  382. }
  383. fclose(devmapf);
  384. }
  385. _thread = Thread::start(this);
  386. }
  387. MacKextEthernetTap::~MacKextEthernetTap()
  388. {
  389. MacDNSHelper::removeDNS(_nwid);
  390. ::write(_shutdownSignalPipe[1], "\0", 1); // causes thread to exit
  391. Thread::join(_thread);
  392. for (std::thread& t : _rxThreads) {
  393. t.join();
  394. }
  395. ::close(_fd);
  396. ::close(_shutdownSignalPipe[0]);
  397. ::close(_shutdownSignalPipe[1]);
  398. {
  399. Mutex::Lock _gl(globalTapCreateLock);
  400. if (--globalTapsRunning <= 0) {
  401. globalTapsRunning = 0; // sanity check -- should not be possible
  402. char tmp[16384];
  403. sprintf(tmp, "%s/%s", _homePath.c_str(), "tap.kext");
  404. long kextpid = (long)fork();
  405. if (kextpid == 0) {
  406. OSUtils::redirectUnixOutputs("/dev/null", (const char*)0);
  407. ::execl("/sbin/kextunload", "/sbin/kextunload", tmp, (const char*)0);
  408. ::_exit(-1);
  409. }
  410. else if (kextpid > 0) {
  411. int exitcode = -1;
  412. ::waitpid(kextpid, &exitcode, 0);
  413. }
  414. }
  415. }
  416. }
  417. void MacKextEthernetTap::setEnabled(bool en)
  418. {
  419. _enabled = en;
  420. // TODO: interface status change
  421. }
  422. bool MacKextEthernetTap::enabled() const
  423. {
  424. return _enabled;
  425. }
  426. bool MacKextEthernetTap::addIp(const InetAddress& ip)
  427. {
  428. if (! ip)
  429. return false;
  430. long cpid = (long)fork();
  431. if (cpid == 0) {
  432. char tmp[128];
  433. ::execl("/sbin/ifconfig", "/sbin/ifconfig", _dev.c_str(), (ip.ss_family == AF_INET6) ? "inet6" : "inet", ip.toString(tmp), "alias", (const char*)0);
  434. ::_exit(-1);
  435. }
  436. else if (cpid > 0) {
  437. int exitcode = -1;
  438. ::waitpid(cpid, &exitcode, 0);
  439. return (exitcode == 0);
  440. } // else return false...
  441. return false;
  442. }
  443. bool MacKextEthernetTap::removeIp(const InetAddress& ip)
  444. {
  445. if (! ip)
  446. return true;
  447. std::vector<InetAddress> allIps(ips());
  448. for (std::vector<InetAddress>::iterator i(allIps.begin()); i != allIps.end(); ++i) {
  449. if (*i == ip) {
  450. long cpid = (long)fork();
  451. if (cpid == 0) {
  452. char tmp[128];
  453. execl("/sbin/ifconfig", "/sbin/ifconfig", _dev.c_str(), (ip.ss_family == AF_INET6) ? "inet6" : "inet", ip.toIpString(tmp), "-alias", (const char*)0);
  454. _exit(-1);
  455. }
  456. else if (cpid > 0) {
  457. int exitcode = -1;
  458. waitpid(cpid, &exitcode, 0);
  459. return (exitcode == 0);
  460. }
  461. }
  462. }
  463. return false;
  464. }
  465. std::vector<InetAddress> MacKextEthernetTap::ips() const
  466. {
  467. struct ifaddrs* ifa = (struct ifaddrs*)0;
  468. if (getifaddrs(&ifa))
  469. return std::vector<InetAddress>();
  470. std::vector<InetAddress> r;
  471. struct ifaddrs* p = ifa;
  472. while (p) {
  473. if ((! strcmp(p->ifa_name, _dev.c_str())) && (p->ifa_addr) && (p->ifa_netmask) && (p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  474. switch (p->ifa_addr->sa_family) {
  475. case AF_INET: {
  476. struct sockaddr_in* sin = (struct sockaddr_in*)p->ifa_addr;
  477. struct sockaddr_in* nm = (struct sockaddr_in*)p->ifa_netmask;
  478. r.push_back(InetAddress(&(sin->sin_addr.s_addr), 4, Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  479. } break;
  480. case AF_INET6: {
  481. struct sockaddr_in6* sin = (struct sockaddr_in6*)p->ifa_addr;
  482. struct sockaddr_in6* nm = (struct sockaddr_in6*)p->ifa_netmask;
  483. uint32_t b[4];
  484. memcpy(b, nm->sin6_addr.s6_addr, sizeof(b));
  485. 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])));
  486. } break;
  487. }
  488. }
  489. p = p->ifa_next;
  490. }
  491. if (ifa)
  492. freeifaddrs(ifa);
  493. std::sort(r.begin(), r.end());
  494. r.erase(std::unique(r.begin(), r.end()), r.end());
  495. return r;
  496. }
  497. void MacKextEthernetTap::put(const MAC& from, const MAC& to, unsigned int etherType, const void* data, unsigned int len)
  498. {
  499. char putBuf[ZT_MAX_MTU + 64];
  500. if ((_fd > 0) && (len <= _mtu) && (_enabled)) {
  501. to.copyTo(putBuf, 6);
  502. from.copyTo(putBuf + 6, 6);
  503. *((uint16_t*)(putBuf + 12)) = htons((uint16_t)etherType);
  504. memcpy(putBuf + 14, data, len);
  505. len += 14;
  506. ::write(_fd, putBuf, len);
  507. }
  508. }
  509. std::string MacKextEthernetTap::deviceName() const
  510. {
  511. return _dev;
  512. }
  513. void MacKextEthernetTap::setFriendlyName(const char* friendlyName)
  514. {
  515. }
  516. void MacKextEthernetTap::scanMulticastGroups(std::vector<MulticastGroup>& added, std::vector<MulticastGroup>& removed)
  517. {
  518. std::vector<MulticastGroup> newGroups;
  519. struct _intl_ifmaddrs* ifmap = (struct _intl_ifmaddrs*)0;
  520. if (! _intl_getifmaddrs(&ifmap)) {
  521. struct _intl_ifmaddrs* p = ifmap;
  522. while (p) {
  523. if (p->ifma_addr->sa_family == AF_LINK) {
  524. struct sockaddr_dl* in = (struct sockaddr_dl*)p->ifma_name;
  525. struct sockaddr_dl* la = (struct sockaddr_dl*)p->ifma_addr;
  526. if ((la->sdl_alen == 6) && (in->sdl_nlen <= _dev.length()) && (! memcmp(_dev.data(), in->sdl_data, in->sdl_nlen)))
  527. newGroups.push_back(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen, 6), 0));
  528. }
  529. p = p->ifma_next;
  530. }
  531. _intl_freeifmaddrs(ifmap);
  532. }
  533. std::vector<InetAddress> allIps(ips());
  534. for (std::vector<InetAddress>::iterator ip(allIps.begin()); ip != allIps.end(); ++ip)
  535. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  536. std::sort(newGroups.begin(), newGroups.end());
  537. std::unique(newGroups.begin(), newGroups.end());
  538. for (std::vector<MulticastGroup>::iterator m(newGroups.begin()); m != newGroups.end(); ++m) {
  539. if (! std::binary_search(_multicastGroups.begin(), _multicastGroups.end(), *m))
  540. added.push_back(*m);
  541. }
  542. for (std::vector<MulticastGroup>::iterator m(_multicastGroups.begin()); m != _multicastGroups.end(); ++m) {
  543. if (! std::binary_search(newGroups.begin(), newGroups.end(), *m))
  544. removed.push_back(*m);
  545. }
  546. _multicastGroups.swap(newGroups);
  547. }
  548. void MacKextEthernetTap::setMtu(unsigned int mtu)
  549. {
  550. if (mtu != _mtu) {
  551. _mtu = mtu;
  552. long cpid = (long)fork();
  553. if (cpid == 0) {
  554. char tmp[64];
  555. OSUtils::ztsnprintf(tmp, sizeof(tmp), "%u", mtu);
  556. execl("/sbin/ifconfig", "/sbin/ifconfig", _dev.c_str(), "mtu", tmp, (const char*)0);
  557. _exit(-1);
  558. }
  559. else if (cpid > 0) {
  560. int exitcode = -1;
  561. waitpid(cpid, &exitcode, 0);
  562. }
  563. }
  564. }
  565. void MacKextEthernetTap::threadMain() throw()
  566. {
  567. fd_set readfds, nullfds;
  568. MAC to, from;
  569. int n, nfds, r;
  570. char getBuf[ZT_MAX_MTU + 64];
  571. Thread::sleep(500);
  572. FD_ZERO(&readfds);
  573. FD_ZERO(&nullfds);
  574. nfds = (int)std::max(_shutdownSignalPipe[0], _fd) + 1;
  575. r = 0;
  576. for (;;) {
  577. FD_SET(_shutdownSignalPipe[0], &readfds);
  578. FD_SET(_fd, &readfds);
  579. select(nfds, &readfds, &nullfds, &nullfds, (struct timeval*)0);
  580. if (FD_ISSET(_shutdownSignalPipe[0], &readfds)) // writes to shutdown pipe terminate thread
  581. break;
  582. if (FD_ISSET(_fd, &readfds)) {
  583. n = (int)::read(_fd, getBuf + r, sizeof(getBuf) - r);
  584. if (n < 0) {
  585. if ((errno != EINTR) && (errno != ETIMEDOUT))
  586. break;
  587. }
  588. else {
  589. // Some tap drivers like to send the ethernet frame and the
  590. // payload in two chunks, so handle that by accumulating
  591. // data until we have at least a frame.
  592. r += n;
  593. if (r > 14) {
  594. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  595. r = _mtu + 14;
  596. if (_enabled) {
  597. to.setTo(getBuf, 6);
  598. from.setTo(getBuf + 6, 6);
  599. unsigned int etherType = ntohs(((const uint16_t*)getBuf)[6]);
  600. // TODO: VLAN support
  601. _handler(_arg, (void*)0, _nwid, from, to, etherType, 0, (const void*)(getBuf + 14), r - 14);
  602. }
  603. r = 0;
  604. }
  605. }
  606. }
  607. }
  608. }
  609. void MacKextEthernetTap::setDns(const char* domain, const std::vector<InetAddress>& servers)
  610. {
  611. MacDNSHelper::setDNS(_nwid, domain, servers);
  612. }
  613. } // namespace ZeroTier