OSXEthernetTap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2015 ZeroTier, Inc.
  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. _handler(handler),
  283. _arg(arg),
  284. _mtu(mtu),
  285. _metric(metric),
  286. _fd(0),
  287. _enabled(true)
  288. {
  289. static Mutex globalTapCreateLock;
  290. char devpath[64],ethaddr[64],mtustr[32],metstr[32];
  291. struct stat stattmp;
  292. Mutex::Lock _gl(globalTapCreateLock);
  293. if (mtu > 2800)
  294. throw std::runtime_error("max tap MTU is 2800");
  295. if (stat("/dev/zt0",&stattmp))
  296. throw std::runtime_error("/dev/zt# tap devices do not exist");
  297. // Try to reopen the last device we had, if we had one and it's still unused.
  298. bool recalledDevice = false;
  299. if ((desiredDevice)&&(desiredDevice[0] == 'z')&&(desiredDevice[1] == 't')) {
  300. if ((strchr(desiredDevice,'/'))||(strchr(desiredDevice,'.'))) // security sanity check
  301. throw std::runtime_error("invalid desiredDevice parameter");
  302. Utils::snprintf(devpath,sizeof(devpath),"/dev/%s",desiredDevice);
  303. if (stat(devpath,&stattmp) == 0) {
  304. _fd = ::open(devpath,O_RDWR);
  305. if (_fd > 0) {
  306. _dev = desiredDevice;
  307. recalledDevice = true;
  308. }
  309. }
  310. }
  311. // Open the first unused tap device if we didn't recall a previous one.
  312. if (!recalledDevice) {
  313. for(int i=0;i<64;++i) {
  314. Utils::snprintf(devpath,sizeof(devpath),"/dev/zt%d",i);
  315. if (stat(devpath,&stattmp))
  316. throw std::runtime_error("no more TAP devices available");
  317. _fd = ::open(devpath,O_RDWR);
  318. if (_fd > 0) {
  319. char foo[16];
  320. Utils::snprintf(foo,sizeof(foo),"zt%d",i);
  321. _dev = foo;
  322. break;
  323. }
  324. }
  325. }
  326. if (_fd <= 0)
  327. throw std::runtime_error("unable to open TAP device or no more devices available");
  328. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  329. ::close(_fd);
  330. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  331. }
  332. // Configure MAC address and MTU, bring interface up
  333. 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]);
  334. Utils::snprintf(mtustr,sizeof(mtustr),"%u",_mtu);
  335. Utils::snprintf(metstr,sizeof(metstr),"%u",_metric);
  336. long cpid = (long)vfork();
  337. if (cpid == 0) {
  338. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"lladdr",ethaddr,"mtu",mtustr,"metric",metstr,"up",(const char *)0);
  339. ::_exit(-1);
  340. } else if (cpid > 0) {
  341. int exitcode = -1;
  342. ::waitpid(cpid,&exitcode,0);
  343. if (exitcode) {
  344. ::close(_fd);
  345. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  346. }
  347. }
  348. _setIpv6Stuff(_dev.c_str(),true,false);
  349. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  350. fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  351. ::pipe(_shutdownSignalPipe);
  352. _thread = Thread::start(this);
  353. }
  354. OSXEthernetTap::~OSXEthernetTap()
  355. {
  356. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  357. Thread::join(_thread);
  358. ::close(_fd);
  359. ::close(_shutdownSignalPipe[0]);
  360. ::close(_shutdownSignalPipe[1]);
  361. }
  362. void OSXEthernetTap::setEnabled(bool en)
  363. {
  364. _enabled = en;
  365. // TODO: interface status change
  366. }
  367. bool OSXEthernetTap::enabled() const
  368. {
  369. return _enabled;
  370. }
  371. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  372. {
  373. long cpid = (long)vfork();
  374. if (cpid == 0) {
  375. execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  376. _exit(-1);
  377. } else if (cpid > 0) {
  378. int exitcode = -1;
  379. waitpid(cpid,&exitcode,0);
  380. return (exitcode == 0);
  381. }
  382. return false; // never reached, make compiler shut up about return value
  383. }
  384. bool OSXEthernetTap::addIP(const InetAddress &ip)
  385. {
  386. if (!ip)
  387. return false;
  388. std::set<InetAddress> allIps(ips());
  389. if (allIps.count(ip) > 0)
  390. return true; // IP/netmask already assigned
  391. // Remove and reconfigure if address is the same but netmask is different
  392. for(std::set<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  393. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  394. if (___removeIp(_dev,*i))
  395. break;
  396. }
  397. }
  398. long cpid = (long)vfork();
  399. if (cpid == 0) {
  400. ::execl("/sbin/ifconfig","/sbin/ifconfig",_dev.c_str(),ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  401. ::_exit(-1);
  402. } else if (cpid > 0) {
  403. int exitcode = -1;
  404. ::waitpid(cpid,&exitcode,0);
  405. return (exitcode == 0);
  406. }
  407. return false;
  408. }
  409. bool OSXEthernetTap::removeIP(const InetAddress &ip)
  410. {
  411. if (ips().count(ip) > 0) {
  412. if (___removeIp(_dev,ip))
  413. return true;
  414. }
  415. return false;
  416. }
  417. std::set<InetAddress> OSXEthernetTap::ips() const
  418. {
  419. struct ifaddrs *ifa = (struct ifaddrs *)0;
  420. if (getifaddrs(&ifa))
  421. return std::set<InetAddress>();
  422. std::set<InetAddress> r;
  423. struct ifaddrs *p = ifa;
  424. while (p) {
  425. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  426. switch(p->ifa_addr->sa_family) {
  427. case AF_INET: {
  428. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  429. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  430. r.insert(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  431. } break;
  432. case AF_INET6: {
  433. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  434. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  435. uint32_t b[4];
  436. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  437. 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])));
  438. } break;
  439. }
  440. }
  441. p = p->ifa_next;
  442. }
  443. if (ifa)
  444. freeifaddrs(ifa);
  445. return r;
  446. }
  447. void OSXEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  448. {
  449. char putBuf[4096];
  450. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  451. to.copyTo(putBuf,6);
  452. from.copyTo(putBuf + 6,6);
  453. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  454. memcpy(putBuf + 14,data,len);
  455. len += 14;
  456. ::write(_fd,putBuf,len);
  457. }
  458. }
  459. std::string OSXEthernetTap::deviceName() const
  460. {
  461. return _dev;
  462. }
  463. void OSXEthernetTap::setFriendlyName(const char *friendlyName)
  464. {
  465. }
  466. bool OSXEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  467. {
  468. std::set<MulticastGroup> newGroups;
  469. struct _intl_ifmaddrs *ifmap = (struct _intl_ifmaddrs *)0;
  470. if (!_intl_getifmaddrs(&ifmap)) {
  471. struct _intl_ifmaddrs *p = ifmap;
  472. while (p) {
  473. if (p->ifma_addr->sa_family == AF_LINK) {
  474. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  475. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  476. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= _dev.length())&&(!memcmp(_dev.data(),in->sdl_data,in->sdl_nlen)))
  477. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen,6),0));
  478. }
  479. p = p->ifma_next;
  480. }
  481. _intl_freeifmaddrs(ifmap);
  482. }
  483. {
  484. std::set<InetAddress> allIps(ips());
  485. for(std::set<InetAddress>::const_iterator i(allIps.begin());i!=allIps.end();++i)
  486. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  487. }
  488. bool changed = false;
  489. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  490. if (!groups.count(*mg)) {
  491. groups.insert(*mg);
  492. changed = true;
  493. }
  494. }
  495. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  496. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  497. groups.erase(mg++);
  498. changed = true;
  499. } else ++mg;
  500. }
  501. return changed;
  502. }
  503. void OSXEthernetTap::threadMain()
  504. throw()
  505. {
  506. fd_set readfds,nullfds;
  507. MAC to,from;
  508. int n,nfds,r;
  509. char getBuf[8194];
  510. Buffer<4096> data;
  511. // Wait for a moment after startup -- wait for Network to finish
  512. // constructing itself.
  513. Thread::sleep(500);
  514. FD_ZERO(&readfds);
  515. FD_ZERO(&nullfds);
  516. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  517. r = 0;
  518. for(;;) {
  519. FD_SET(_shutdownSignalPipe[0],&readfds);
  520. FD_SET(_fd,&readfds);
  521. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  522. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  523. break;
  524. if (FD_ISSET(_fd,&readfds)) {
  525. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  526. if (n < 0) {
  527. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  528. break;
  529. } else {
  530. // Some tap drivers like to send the ethernet frame and the
  531. // payload in two chunks, so handle that by accumulating
  532. // data until we have at least a frame.
  533. r += n;
  534. if (r > 14) {
  535. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  536. r = _mtu + 14;
  537. if (_enabled) {
  538. to.setTo(getBuf,6);
  539. from.setTo(getBuf + 6,6);
  540. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  541. data.copyFrom(getBuf + 14,(unsigned int)r - 14);
  542. _handler(_arg,from,to,etherType,data);
  543. }
  544. r = 0;
  545. }
  546. }
  547. }
  548. }
  549. }
  550. } // namespace ZeroTier