2
0

MacKextEthernetTap.cpp 18 KB

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