OSXEthernetTap.cpp 18 KB

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