OSXEthernetTap.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  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. #include <netinet6/nd6.h>
  57. #include <ifaddrs.h>
  58. // OSX compile fix... in6_var defines this in a struct which namespaces it for C++
  59. struct prf_ra {
  60. u_char onlink : 1;
  61. u_char autonomous : 1;
  62. u_char reserved : 6;
  63. } prf_ra;
  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 "../Constants.hpp"
  235. #include "../Utils.hpp"
  236. #include "../Mutex.hpp"
  237. #include "OSXEthernetTap.hpp"
  238. // ff:ff:ff:ff:ff:ff with no ADI
  239. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  240. static inline bool _setIpv6Stuff(const char *ifname,bool performNUD,bool acceptRouterAdverts)
  241. {
  242. struct in6_ndireq nd;
  243. struct in6_ifreq ifr;
  244. int s = socket(AF_INET6,SOCK_DGRAM,0);
  245. if (s <= 0)
  246. return false;
  247. memset(&nd,0,sizeof(nd));
  248. strncpy(nd.ifname,ifname,sizeof(nd.ifname));
  249. if (ioctl(s,SIOCGIFINFO_IN6,&nd)) {
  250. close(s);
  251. return false;
  252. }
  253. unsigned long oldFlags = (unsigned long)nd.ndi.flags;
  254. if (performNUD)
  255. nd.ndi.flags |= ND6_IFF_PERFORMNUD;
  256. else nd.ndi.flags &= ~ND6_IFF_PERFORMNUD;
  257. if (oldFlags != (unsigned long)nd.ndi.flags) {
  258. if (ioctl(s,SIOCSIFINFO_FLAGS,&nd)) {
  259. close(s);
  260. return false;
  261. }
  262. }
  263. memset(&ifr,0,sizeof(ifr));
  264. strncpy(ifr.ifr_name,ifname,sizeof(ifr.ifr_name));
  265. if (ioctl(s,acceptRouterAdverts ? SIOCAUTOCONF_START : SIOCAUTOCONF_STOP,&ifr)) {
  266. close(s);
  267. return false;
  268. }
  269. close(s);
  270. return true;
  271. }
  272. namespace ZeroTier {
  273. // Only permit one tap to be opened concurrently across the entire process
  274. static Mutex __tapCreateLock;
  275. OSXEthernetTap::OSXEthernetTap(
  276. const RuntimeEnvironment *renv,
  277. const char *tryToGetDevice,
  278. const MAC &mac,
  279. unsigned int mtu,
  280. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  281. void *arg)
  282. throw(std::runtime_error) :
  283. EthernetTap("OSXEthernetTap",mac,mtu,metric),
  284. _r(renv),
  285. _handler(handler),
  286. _arg(arg),
  287. _fd(0),
  288. _enabled(true)
  289. {
  290. char devpath[64],ethaddr[64],mtustr[16],tmp[4096];
  291. struct stat stattmp;
  292. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  293. if (mtu > 2800)
  294. throw std::runtime_error("max tap MTU is 2800");
  295. // Check for existence of ZT tap devices, try to load module if not there
  296. const char *kextload = UNIX_COMMANDS[ZT_MAC_KEXTLOAD_COMMAND];
  297. if ((stat("/dev/zt0",&stattmp))&&(kextload)) {
  298. strcpy(tmp,_r->homePath.c_str());
  299. long kextpid = (long)vfork();
  300. if (kextpid == 0) {
  301. chdir(tmp);
  302. execl(kextload,kextload,"-q","-repository",tmp,"tap.kext",(const char *)0);
  303. _exit(-1);
  304. } else if (kextpid > 0) {
  305. int exitcode = -1;
  306. waitpid(kextpid,&exitcode,0);
  307. usleep(500);
  308. } else throw std::runtime_error("unable to create subprocess with fork()");
  309. }
  310. if (stat("/dev/zt0",&stattmp))
  311. throw std::runtime_error("/dev/zt# tap devices do not exist and unable to load kernel extension");
  312. // Try to reopen the last device we had, if we had one and it's still unused.
  313. bool recalledDevice = false;
  314. if ((tryToGetDevice)&&(tryToGetDevice[0])) {
  315. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",tryToGetDevice);
  316. if (stat(devpath,&stattmp) == 0) {
  317. _fd = ::open(devpath,O_RDWR);
  318. if (_fd > 0) {
  319. _dev = tryToGetDevice;
  320. recalledDevice = true;
  321. }
  322. }
  323. }
  324. // Open the first unused tap device if we didn't recall a previous one.
  325. if (!recalledDevice) {
  326. for(int i=0;i<256;++i) {
  327. Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
  328. if (stat(devpath,&stattmp))
  329. throw std::runtime_error("no more TAP devices available");
  330. _fd = ::open(devpath,O_RDWR);
  331. if (_fd > 0) {
  332. char foo[16];
  333. Utils::snprintf(foo,sizeof(foo),"zt%d",i);
  334. _dev = foo;
  335. break;
  336. }
  337. }
  338. }
  339. if (_fd <= 0)
  340. throw std::runtime_error("unable to open TAP device or no more devices available");
  341. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  342. ::close(_fd);
  343. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  344. }
  345. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  346. if (!ifconfig) {
  347. ::close(_fd);
  348. throw std::runtime_error("unable to find 'ifconfig' command on system");
  349. }
  350. // Configure MAC address and MTU, bring interface up
  351. 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]);
  352. Utils::snprintf(mtustr,sizeof(mtustr),"%u",mtu);
  353. long cpid;
  354. if ((cpid = (long)vfork()) == 0) {
  355. execl(ifconfig,ifconfig,_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"up",(const char *)0);
  356. _exit(-1);
  357. } else {
  358. int exitcode = -1;
  359. waitpid(cpid,&exitcode,0);
  360. if (exitcode) {
  361. ::close(_fd);
  362. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  363. }
  364. }
  365. _setIpv6Stuff(_dev.c_str(),true,false);
  366. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  367. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  368. ::pipe(_shutdownSignalPipe);
  369. _thread = Thread::start(this);
  370. EthernetTap_instances_m.lock();
  371. ++EthernetTap_instances;
  372. EthernetTap_instances_m.unlock();
  373. }
  374. OSXEthernetTap::~OSXEthernetTap()
  375. {
  376. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  377. Thread::join(_thread);
  378. ::close(_fd);
  379. ::close(_shutdownSignalPipe[0]);
  380. ::close(_shutdownSignalPipe[1]);
  381. EthernetTap_instances_m.lock();
  382. int instances = --EthernetTap_instances;
  383. EthernetTap_instances_m.unlock();
  384. if (instances <= 0) {
  385. // Unload OSX kernel extension on the deletion of the last EthernetTap
  386. // instance.
  387. const char *kextunload = UNIX_COMMANDS[ZT_MAC_KEXTUNLOAD_COMMAND];
  388. if (kextunload) {
  389. char tmp[4096];
  390. sprintf(tmp,"%s/tap.kext",_r->homePath.c_str());
  391. long kextpid = (long)vfork();
  392. if (kextpid == 0) {
  393. execl(kextunload,kextunload,tmp,(const char *)0);
  394. _exit(-1);
  395. } else if (kextpid > 0) {
  396. int exitcode = -1;
  397. waitpid(kextpid,&exitcode,0);
  398. }
  399. }
  400. }
  401. }
  402. void OSXEthernetTap::setEnabled(bool en)
  403. {
  404. _enabled = en;
  405. // TODO: interface status change
  406. }
  407. bool OSXEthernetTap::enabled() const
  408. {
  409. return _enabled;
  410. }
  411. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  412. {
  413. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  414. if (!ifconfig)
  415. return false;
  416. long cpid;
  417. if ((cpid = (long)vfork()) == 0) {
  418. execl(ifconfig,ifconfig,_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  419. _exit(-1);
  420. } else {
  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. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  430. if (!ifconfig) {
  431. LOG("ERROR: could not configure IP address for %s: unable to find 'ifconfig' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev.c_str());
  432. return false;
  433. }
  434. if (!ip)
  435. return false;
  436. std::set<InetAddress> allIps(ips());
  437. if (allIps.count(ip) > 0)
  438. return true; // IP/netmask already assigned
  439. // Remove and reconfigure if address is the same but netmask is different
  440. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  441. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  442. if (___removeIp(_dev,*i)) {
  443. break;
  444. } else {
  445. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  446. }
  447. }
  448. }
  449. long cpid;
  450. if ((cpid = (long)vfork()) == 0) {
  451. execl(ifconfig,ifconfig,_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  452. _exit(-1);
  453. } else {
  454. int exitcode = -1;
  455. waitpid(cpid,&exitcode,0);
  456. return (exitcode == 0);
  457. }
  458. return false;
  459. }
  460. bool OSXEthernetTap::removeIP(const InetAddress &ip)
  461. {
  462. if (ips().count(ip) > 0) {
  463. if (___removeIp(_dev,ip))
  464. return true;
  465. }
  466. return false;
  467. }
  468. std::set<InetAddress> OSXEthernetTap::ips() const
  469. {
  470. struct ifaddrs *ifa = (struct ifaddrs *)0;
  471. if (getifaddrs(&ifa))
  472. return std::set<InetAddress>();
  473. std::set<InetAddress> r;
  474. struct ifaddrs *p = ifa;
  475. while (p) {
  476. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  477. switch(p->ifa_addr->sa_family) {
  478. case AF_INET: {
  479. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  480. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  481. r.insert(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  482. } break;
  483. case AF_INET6: {
  484. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  485. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  486. uint32_t b[4];
  487. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  488. r.insert(InetAddress(sin->sin6_addr.s6_addr,16,Utils::countBits(b[0]) + Utils::countBits(b[1]) + Utils::countBits(b[2]) + Utils::countBits(b[3])));
  489. } break;
  490. }
  491. }
  492. p = p->ifa_next;
  493. }
  494. if (ifa)
  495. freeifaddrs(ifa);
  496. return r;
  497. }
  498. void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  499. {
  500. char putBuf[4096 + 14];
  501. if ((_fd > 0)&&(len <= _mtu)) {
  502. to.copyTo(putBuf,6);
  503. from.copyTo(putBuf + 6,6);
  504. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  505. memcpy(putBuf + 14,data,len);
  506. len += 14;
  507. int n = ::write(_fd,putBuf,len);
  508. if (n <= 0) {
  509. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  510. } else if (n != (int)len) {
  511. // Saw this gremlin once, so log it if we see it again... OSX tap
  512. // or something seems to have goofy issues with certain MTUs.
  513. LOG("ERROR: write underrun: %s tap write() wrote %d of %u bytes of frame",_dev.c_str(),n,len);
  514. }
  515. }
  516. }
  517. std::string OSXEthernetTap::deviceName() const
  518. {
  519. return _dev;
  520. }
  521. std::string OSXEthernetTap::persistentId() const
  522. {
  523. return std::string();
  524. }
  525. bool OSXEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  526. {
  527. std::set<MulticastGroup> newGroups;
  528. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  529. if (!_intl_getifmaddrs(&ifmap)) {
  530. struct _intl_ifmaddrs *p = ifmap;
  531. while (p) {
  532. if (p->ifma_addr->sa_family == AF_LINK) {
  533. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  534. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  535. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  536. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  537. }
  538. p = p->ifma_next;
  539. }
  540. _intl_freeifmaddrs(ifmap);
  541. }
  542. {
  543. std::set<InetAddress> allIps(ips());
  544. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  545. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  546. }
  547. bool changed = false;
  548. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  549. if (!groups.count(*mg)) {
  550. groups.insert(*mg);
  551. changed = true;
  552. }
  553. }
  554. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  555. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  556. groups.erase(mg++);
  557. changed = true;
  558. } else ++mg;
  559. }
  560. return changed;
  561. }
  562. void OSXEthernetTap::threadMain()
  563. throw()
  564. {
  565. fd_set readfds,nullfds;
  566. MAC to,from;
  567. int n,nfds,r;
  568. char getBuf[8194];
  569. Buffer<4096> data;
  570. // Wait for a moment after startup -- wait for Network to finish
  571. // constructing itself.
  572. Thread::sleep(500);
  573. FD_ZERO(&readfds);
  574. FD_ZERO(&nullfds);
  575. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  576. r = 0;
  577. for(;;) {
  578. FD_SET(_shutdownSignalPipe[0],&readfds);
  579. FD_SET(_fd,&readfds);
  580. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  581. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  582. break;
  583. if (FD_ISSET(_fd,&readfds)) {
  584. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  585. if (n < 0) {
  586. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  587. TRACE("unexpected error reading from tap: %s",strerror(errno));
  588. break;
  589. }
  590. } else {
  591. // Some tap drivers like to send the ethernet frame and the
  592. // payload in two chunks, so handle that by accumulating
  593. // data until we have at least a frame.
  594. r += n;
  595. if (r > 14) {
  596. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  597. r = _mtu + 14;
  598. to.setTo(getBuf,6);
  599. from.setTo(getBuf + 6,6);
  600. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  601. if (etherType != 0x8100) { // VLAN tagged frames are not supported!
  602. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  603. _handler(_arg,from,to,etherType,data);
  604. }
  605. r = 0;
  606. }
  607. }
  608. }
  609. }
  610. }
  611. } // namespace ZeroTier