OSXEthernetTap.cpp 18 KB

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