OSXEthernetTap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. // OSX compile fix... in6_var defines this in a struct which namespaces it for C++ ... why?!?
  57. struct prf_ra {
  58. u_char onlink : 1;
  59. u_char autonomous : 1;
  60. u_char reserved : 6;
  61. } prf_ra;
  62. #include <netinet6/nd6.h>
  63. #include <ifaddrs.h>
  64. // These are KERNEL_PRIVATE... why?
  65. #ifndef SIOCAUTOCONF_START
  66. #define SIOCAUTOCONF_START _IOWR('i', 132, struct in6_ifreq) /* accept rtadvd on this interface */
  67. #endif
  68. #ifndef SIOCAUTOCONF_STOP
  69. #define SIOCAUTOCONF_STOP _IOWR('i', 133, struct in6_ifreq) /* stop accepting rtadv for this interface */
  70. #endif
  71. // --------------------------------------------------------------------------
  72. // --------------------------------------------------------------------------
  73. // This source is from:
  74. // http://www.opensource.apple.com/source/Libinfo/Libinfo-406.17/gen.subproj/getifmaddrs.c?txt
  75. // It's here because OSX 10.6 does not have this convenience function.
  76. #define SALIGN (sizeof(uint32_t) - 1)
  77. #define SA_RLEN(sa) ((sa)->sa_len ? (((sa)->sa_len + SALIGN) & ~SALIGN) : \
  78. (SALIGN + 1))
  79. #define MAX_SYSCTL_TRY 5
  80. #define RTA_MASKS (RTA_GATEWAY | RTA_IFP | RTA_IFA)
  81. /* FreeBSD uses NET_RT_IFMALIST and RTM_NEWMADDR from <sys/socket.h> */
  82. /* We can use NET_RT_IFLIST2 and RTM_NEWMADDR2 on Darwin */
  83. //#define DARWIN_COMPAT
  84. //#ifdef DARWIN_COMPAT
  85. #define GIM_SYSCTL_MIB NET_RT_IFLIST2
  86. #define GIM_RTM_ADDR RTM_NEWMADDR2
  87. //#else
  88. //#define GIM_SYSCTL_MIB NET_RT_IFMALIST
  89. //#define GIM_RTM_ADDR RTM_NEWMADDR
  90. //#endif
  91. // Not in 10.6 includes so use our own
  92. struct _intl_ifmaddrs {
  93. struct _intl_ifmaddrs *ifma_next;
  94. struct sockaddr *ifma_name;
  95. struct sockaddr *ifma_addr;
  96. struct sockaddr *ifma_lladdr;
  97. };
  98. static inline int _intl_getifmaddrs(struct _intl_ifmaddrs **pif)
  99. {
  100. int icnt = 1;
  101. int dcnt = 0;
  102. int ntry = 0;
  103. size_t len;
  104. size_t needed;
  105. int mib[6];
  106. int i;
  107. char *buf;
  108. char *data;
  109. char *next;
  110. char *p;
  111. struct ifma_msghdr2 *ifmam;
  112. struct _intl_ifmaddrs *ifa, *ift;
  113. struct rt_msghdr *rtm;
  114. struct sockaddr *sa;
  115. mib[0] = CTL_NET;
  116. mib[1] = PF_ROUTE;
  117. mib[2] = 0; /* protocol */
  118. mib[3] = 0; /* wildcard address family */
  119. mib[4] = GIM_SYSCTL_MIB;
  120. mib[5] = 0; /* no flags */
  121. do {
  122. if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0)
  123. return (-1);
  124. if ((buf = (char *)malloc(needed)) == NULL)
  125. return (-1);
  126. if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
  127. if (errno != ENOMEM || ++ntry >= MAX_SYSCTL_TRY) {
  128. free(buf);
  129. return (-1);
  130. }
  131. free(buf);
  132. buf = NULL;
  133. }
  134. } while (buf == NULL);
  135. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  136. rtm = (struct rt_msghdr *)(void *)next;
  137. if (rtm->rtm_version != RTM_VERSION)
  138. continue;
  139. switch (rtm->rtm_type) {
  140. case GIM_RTM_ADDR:
  141. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  142. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  143. break;
  144. icnt++;
  145. p = (char *)(ifmam + 1);
  146. for (i = 0; i < RTAX_MAX; i++) {
  147. if ((RTA_MASKS & ifmam->ifmam_addrs &
  148. (1 << i)) == 0)
  149. continue;
  150. sa = (struct sockaddr *)(void *)p;
  151. len = SA_RLEN(sa);
  152. dcnt += len;
  153. p += len;
  154. }
  155. break;
  156. }
  157. }
  158. data = (char *)malloc(sizeof(struct _intl_ifmaddrs) * icnt + dcnt);
  159. if (data == NULL) {
  160. free(buf);
  161. return (-1);
  162. }
  163. ifa = (struct _intl_ifmaddrs *)(void *)data;
  164. data += sizeof(struct _intl_ifmaddrs) * icnt;
  165. memset(ifa, 0, sizeof(struct _intl_ifmaddrs) * icnt);
  166. ift = ifa;
  167. for (next = buf; next < buf + needed; next += rtm->rtm_msglen) {
  168. rtm = (struct rt_msghdr *)(void *)next;
  169. if (rtm->rtm_version != RTM_VERSION)
  170. continue;
  171. switch (rtm->rtm_type) {
  172. case GIM_RTM_ADDR:
  173. ifmam = (struct ifma_msghdr2 *)(void *)rtm;
  174. if ((ifmam->ifmam_addrs & RTA_IFA) == 0)
  175. break;
  176. p = (char *)(ifmam + 1);
  177. for (i = 0; i < RTAX_MAX; i++) {
  178. if ((RTA_MASKS & ifmam->ifmam_addrs &
  179. (1 << i)) == 0)
  180. continue;
  181. sa = (struct sockaddr *)(void *)p;
  182. len = SA_RLEN(sa);
  183. switch (i) {
  184. case RTAX_GATEWAY:
  185. ift->ifma_lladdr =
  186. (struct sockaddr *)(void *)data;
  187. memcpy(data, p, len);
  188. data += len;
  189. break;
  190. case RTAX_IFP:
  191. ift->ifma_name =
  192. (struct sockaddr *)(void *)data;
  193. memcpy(data, p, len);
  194. data += len;
  195. break;
  196. case RTAX_IFA:
  197. ift->ifma_addr =
  198. (struct sockaddr *)(void *)data;
  199. memcpy(data, p, len);
  200. data += len;
  201. break;
  202. default:
  203. data += len;
  204. break;
  205. }
  206. p += len;
  207. }
  208. ift->ifma_next = ift + 1;
  209. ift = ift->ifma_next;
  210. break;
  211. }
  212. }
  213. free(buf);
  214. if (ift > ifa) {
  215. ift--;
  216. ift->ifma_next = NULL;
  217. *pif = ifa;
  218. } else {
  219. *pif = NULL;
  220. free(ifa);
  221. }
  222. return (0);
  223. }
  224. static inline void _intl_freeifmaddrs(struct _intl_ifmaddrs *ifmp)
  225. {
  226. free(ifmp);
  227. }
  228. // --------------------------------------------------------------------------
  229. // --------------------------------------------------------------------------
  230. #include <string>
  231. #include <map>
  232. #include <set>
  233. #include <algorithm>
  234. #include "../node/Constants.hpp"
  235. #include "../node/Utils.hpp"
  236. #include "../node/Mutex.hpp"
  237. #include "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. OSXEthernetTap::OSXEthernetTap(
  274. const MAC &mac,
  275. unsigned int mtu,
  276. unsigned int metric,
  277. uint64_t nwid,
  278. const char *desiredDevice,
  279. const char *friendlyName,
  280. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  281. void *arg) :
  282. EthernetTap("OSXEthernetTap",mac,mtu,metric),
  283. _handler(handler),
  284. _arg(arg),
  285. _mtu(mtu),
  286. _metric(metric),
  287. _fd(0),
  288. _enabled(true)
  289. {
  290. static Mutex globalTapCreateLock;
  291. char devpath[64],ethaddr[64],mtustr[32],metstr[32];
  292. struct stat stattmp;
  293. Mutex::Lock _gl(globalTapCreateLock);
  294. if (mtu > 2800)
  295. throw std::runtime_error("max tap MTU is 2800");
  296. if (stat("/dev/zt0",&stattmp))
  297. throw std::runtime_error("/dev/zt# tap devices do not exist");
  298. // Try to reopen the last device we had, if we had one and it's still unused.
  299. bool recalledDevice = false;
  300. if ((desiredDevice)&&(desiredDevice[0] == 'z')&&(desiredDevice[1] == 't')) {
  301. if ((strchr(desiredDevice,'/'))||(strchr(desiredDevice,'.'))) // security sanity check
  302. throw std::runtime_error("invalid desiredDevice parameter");
  303. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",desiredDevice);
  304. if (stat(devpath,&stattmp) == 0) {
  305. _fd = ::open(devpath,O_RDWR);
  306. if (_fd > 0) {
  307. _dev = desiredDevice;
  308. recalledDevice = true;
  309. }
  310. }
  311. }
  312. // Open the first unused tap device if we didn't recall a previous one.
  313. if (!recalledDevice) {
  314. for(int i=0;i<64;++i) {
  315. Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
  316. if (stat(devpath,&stattmp))
  317. throw std::runtime_error("no more TAP devices available");
  318. _fd = ::open(devpath,O_RDWR);
  319. if (_fd > 0) {
  320. char foo[16];
  321. Utils::snprintf(foo,sizeof(foo),"zt%d",i);
  322. _dev = foo;
  323. break;
  324. }
  325. }
  326. }
  327. if (_fd <= 0)
  328. throw std::runtime_error("unable to open TAP device or no more devices available");
  329. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  330. ::close(_fd);
  331. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  332. }
  333. // Configure MAC address and MTU, bring interface up
  334. 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]);
  335. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  336. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  337. long cpid = (long)vfork();
  338. if (cpid == 0) {
  339. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  340. ::_exit(-1);
  341. } else if (cpid > 0) {
  342. int exitcode = -1;
  343. ::waitpid(cpid,&exitcode,0);
  344. if (exitcode) {
  345. ::close(_fd);
  346. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  347. }
  348. }
  349. _setIpv6Stuff(_dev.c_str(),true,false);
  350. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  351. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  352. ::pipe(_shutdownSignalPipe);
  353. _thread = Thread::start(this);
  354. }
  355. OSXEthernetTap::~OSXEthernetTap()
  356. {
  357. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  358. Thread::join(_thread);
  359. ::close(_fd);
  360. ::close(_shutdownSignalPipe[0]);
  361. ::close(_shutdownSignalPipe[1]);
  362. }
  363. void OSXEthernetTap::setEnabled(bool en)
  364. {
  365. _enabled = en;
  366. // TODO: interface status change
  367. }
  368. bool OSXEthernetTap::enabled() const
  369. {
  370. return _enabled;
  371. }
  372. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  373. {
  374. long cpid = (long)vfork();
  375. if (cpid == 0) {
  376. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  377. _exit(-1);
  378. } else if (cpid > 0) {
  379. int exitcode = -1;
  380. waitpid(cpid,&exitcode,0);
  381. return (exitcode == 0);
  382. }
  383. return false; // never reached, make compiler shut up about return value
  384. }
  385. bool OSXEthernetTap::addIP(const InetAddress &ip)
  386. {
  387. if (!ip)
  388. return false;
  389. std::set<InetAddress> allIps(ips());
  390. if (allIps.count(ip) > 0)
  391. return true; // IP/netmask already assigned
  392. // Remove and reconfigure if address is the same but netmask is different
  393. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  394. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  395. if (___removeIp(_dev,*i))
  396. break;
  397. }
  398. }
  399. long cpid = (long)vfork();
  400. if (cpid == 0) {
  401. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  402. ::_exit(-1);
  403. } else if (cpid > 0) {
  404. int exitcode = -1;
  405. ::waitpid(cpid,&exitcode,0);
  406. return (exitcode == 0);
  407. }
  408. return false;
  409. }
  410. bool OSXEthernetTap::removeIP(const InetAddress &ip)
  411. {
  412. if (ips().count(ip) > 0) {
  413. if (___removeIp(_dev,ip))
  414. return true;
  415. }
  416. return false;
  417. }
  418. std::set<InetAddress> OSXEthernetTap::ips() const
  419. {
  420. struct ifaddrs *ifa = (struct ifaddrs *)0;
  421. if (getifaddrs(&ifa))
  422. return std::set<InetAddress>();
  423. std::set<InetAddress> r;
  424. struct ifaddrs *p = ifa;
  425. while (p) {
  426. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  427. switch(p->ifa_addr->sa_family) {
  428. case AF_INET: {
  429. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  430. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  431. r.insert(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  432. } break;
  433. case AF_INET6: {
  434. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  435. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  436. uint32_t b[4];
  437. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  438. 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])));
  439. } break;
  440. }
  441. }
  442. p = p->ifa_next;
  443. }
  444. if (ifa)
  445. freeifaddrs(ifa);
  446. return r;
  447. }
  448. void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  449. {
  450. char putBuf[4096];
  451. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  452. to.copyTo(putBuf,6);
  453. from.copyTo(putBuf + 6,6);
  454. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  455. memcpy(putBuf + 14,data,len);
  456. len += 14;
  457. ::write(_fd,putBuf,len);
  458. }
  459. }
  460. std::string OSXEthernetTap::deviceName() const
  461. {
  462. return _dev;
  463. }
  464. void OSXEthernetTap::setFriendlyName(const char *friendlyName)
  465. {
  466. }
  467. bool OSXEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  468. {
  469. std::set<MulticastGroup> newGroups;
  470. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  471. if (!_intl_getifmaddrs(&ifmap)) {
  472. struct _intl_ifmaddrs *p = ifmap;
  473. while (p) {
  474. if (p->ifma_addr->sa_family == AF_LINK) {
  475. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  476. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  477. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  478. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  479. }
  480. p = p->ifma_next;
  481. }
  482. _intl_freeifmaddrs(ifmap);
  483. }
  484. {
  485. std::set<InetAddress> allIps(ips());
  486. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  487. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  488. }
  489. bool changed = false;
  490. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  491. if (!groups.count(*mg)) {
  492. groups.insert(*mg);
  493. changed = true;
  494. }
  495. }
  496. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  497. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  498. groups.erase(mg++);
  499. changed = true;
  500. } else ++mg;
  501. }
  502. return changed;
  503. }
  504. void OSXEthernetTap::threadMain()
  505. throw()
  506. {
  507. fd_set readfds,nullfds;
  508. MAC to,from;
  509. int n,nfds,r;
  510. char getBuf[8194];
  511. Buffer<4096> data;
  512. // Wait for a moment after startup -- wait for Network to finish
  513. // constructing itself.
  514. Thread::sleep(500);
  515. FD_ZERO(&readfds);
  516. FD_ZERO(&nullfds);
  517. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  518. r = 0;
  519. for(;;) {
  520. FD_SET(_shutdownSignalPipe[0],&readfds);
  521. FD_SET(_fd,&readfds);
  522. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  523. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  524. break;
  525. if (FD_ISSET(_fd,&readfds)) {
  526. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  527. if (n < 0) {
  528. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  529. break;
  530. } else {
  531. // Some tap drivers like to send the ethernet frame and the
  532. // payload in two chunks, so handle that by accumulating
  533. // data until we have at least a frame.
  534. r += n;
  535. if (r > 14) {
  536. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  537. r = _mtu + 14;
  538. if (_enabled) {
  539. to.setTo(getBuf,6);
  540. from.setTo(getBuf + 6,6);
  541. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  542. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  543. _handler(_arg,from,to,etherType,data);
  544. }
  545. r = 0;
  546. }
  547. }
  548. }
  549. }
  550. }
  551. } // namespace ZeroTier