OSXEthernetTap.cpp 19 KB

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