MacKextEthernetTap.cpp 18 KB

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