LinuxEthernetTap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 <unistd.h>
  31. #include <signal.h>
  32. #include <fcntl.h>
  33. #include <errno.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 <netinet/in.h>
  40. #include <net/if_arp.h>
  41. #include <arpa/inet.h>
  42. #include <linux/if.h>
  43. #include <linux/if_tun.h>
  44. #include <linux/if_addr.h>
  45. #include <linux/if_ether.h>
  46. #include <ifaddrs.h>
  47. #include <algorithm>
  48. #include <utility>
  49. #include <string>
  50. #include "../node/Constants.hpp"
  51. #include "../node/Utils.hpp"
  52. #include "../node/Mutex.hpp"
  53. #include "../node/Dictionary.hpp"
  54. #include "OSUtils.hpp"
  55. #include "LinuxEthernetTap.hpp"
  56. // ff:ff:ff:ff:ff:ff with no ADI
  57. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  58. namespace ZeroTier {
  59. static Mutex __tapCreateLock;
  60. static const char _base32_chars[32] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','2','3','4','5','6','7' };
  61. static void _base32_5_to_8(const uint8_t *in,char *out)
  62. {
  63. out[0] = _base32_chars[(in[0]) >> 3];
  64. out[1] = _base32_chars[(in[0] & 0x07) << 2 | (in[1] & 0xc0) >> 6];
  65. out[2] = _base32_chars[(in[1] & 0x3e) >> 1];
  66. out[3] = _base32_chars[(in[1] & 0x01) << 4 | (in[2] & 0xf0) >> 4];
  67. out[4] = _base32_chars[(in[2] & 0x0f) << 1 | (in[3] & 0x80) >> 7];
  68. out[5] = _base32_chars[(in[3] & 0x7c) >> 2];
  69. out[6] = _base32_chars[(in[3] & 0x03) << 3 | (in[4] & 0xe0) >> 5];
  70. out[7] = _base32_chars[(in[4] & 0x1f)];
  71. }
  72. LinuxEthernetTap::LinuxEthernetTap(
  73. const char *homePath,
  74. const MAC &mac,
  75. unsigned int mtu,
  76. unsigned int metric,
  77. uint64_t nwid,
  78. const char *friendlyName,
  79. void (*handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  80. void *arg) :
  81. _handler(handler),
  82. _arg(arg),
  83. _nwid(nwid),
  84. _homePath(homePath),
  85. _mtu(mtu),
  86. _fd(0),
  87. _enabled(true)
  88. {
  89. char procpath[128],nwids[32];
  90. struct stat sbuf;
  91. OSUtils::ztsnprintf(nwids,sizeof(nwids),"%.16llx",nwid);
  92. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  93. _fd = ::open("/dev/net/tun",O_RDWR);
  94. if (_fd <= 0) {
  95. _fd = ::open("/dev/tun",O_RDWR);
  96. if (_fd <= 0)
  97. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  98. }
  99. struct ifreq ifr;
  100. memset(&ifr,0,sizeof(ifr));
  101. // Restore device names from legacy devicemap, but for new devices we use a base32-based canonical naming
  102. std::map<std::string,std::string> globalDeviceMap;
  103. FILE *devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"r");
  104. if (devmapf) {
  105. char buf[256];
  106. while (fgets(buf,sizeof(buf),devmapf)) {
  107. char *x = (char *)0;
  108. char *y = (char *)0;
  109. char *saveptr = (char *)0;
  110. for(char *f=Utils::stok(buf,"\r\n=",&saveptr);(f);f=Utils::stok((char *)0,"\r\n=",&saveptr)) {
  111. if (!x) x = f;
  112. else if (!y) y = f;
  113. else break;
  114. }
  115. if ((x)&&(y)&&(x[0])&&(y[0]))
  116. globalDeviceMap[x] = y;
  117. }
  118. fclose(devmapf);
  119. }
  120. bool recalledDevice = false;
  121. std::map<std::string,std::string>::const_iterator gdmEntry = globalDeviceMap.find(nwids);
  122. if (gdmEntry != globalDeviceMap.end()) {
  123. Utils::scopy(ifr.ifr_name,sizeof(ifr.ifr_name),gdmEntry->second.c_str());
  124. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  125. recalledDevice = (stat(procpath,&sbuf) != 0);
  126. }
  127. if (!recalledDevice) {
  128. #ifdef __SYNOLOGY__
  129. int devno = 50;
  130. do {
  131. OSUtils::ztsnprintf(ifr.ifr_name,sizeof(ifr.ifr_name),"eth%d",devno++);
  132. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  133. } while (stat(procpath,&sbuf) == 0); // try zt#++ until we find one that does not exist
  134. #else
  135. char devno = 0;
  136. do {
  137. uint64_t tmp2[2];
  138. tmp2[0] = Utils::hton(nwid);
  139. tmp2[1] = 0;
  140. char tmp3[17];
  141. tmp3[0] = 'z';
  142. tmp3[1] = 't' + (devno++);
  143. _base32_5_to_8(reinterpret_cast<const uint8_t *>(tmp2),tmp3 + 2);
  144. _base32_5_to_8(reinterpret_cast<const uint8_t *>(tmp2) + 5,tmp3 + 10);
  145. tmp3[15] = (char)0;
  146. memcpy(ifr.ifr_name,tmp3,16);
  147. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  148. } while (stat(procpath,&sbuf) == 0);
  149. #endif
  150. }
  151. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  152. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  153. ::close(_fd);
  154. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  155. }
  156. _dev = ifr.ifr_name;
  157. ::ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  158. // Open an arbitrary socket to talk to netlink
  159. int sock = socket(AF_INET,SOCK_DGRAM,0);
  160. if (sock <= 0) {
  161. ::close(_fd);
  162. throw std::runtime_error("unable to open netlink socket");
  163. }
  164. // Set MAC address
  165. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  166. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  167. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  168. ::close(_fd);
  169. ::close(sock);
  170. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  171. return;
  172. }
  173. // Set MTU
  174. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  175. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  176. ::close(_fd);
  177. ::close(sock);
  178. throw std::runtime_error("unable to configure TAP MTU");
  179. }
  180. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  181. ::close(_fd);
  182. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  183. }
  184. /* Bring interface up */
  185. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  186. ::close(_fd);
  187. ::close(sock);
  188. throw std::runtime_error("unable to get TAP interface flags");
  189. }
  190. ifr.ifr_flags |= IFF_UP;
  191. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  192. ::close(_fd);
  193. ::close(sock);
  194. throw std::runtime_error("unable to set TAP interface flags");
  195. }
  196. ::close(sock);
  197. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  198. ::fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  199. (void)::pipe(_shutdownSignalPipe);
  200. /*
  201. globalDeviceMap[nwids] = _dev;
  202. devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"w");
  203. if (devmapf) {
  204. gdmEntry = globalDeviceMap.begin();
  205. while (gdmEntry != globalDeviceMap.end()) {
  206. fprintf(devmapf,"%s=%s\n",gdmEntry->first.c_str(),gdmEntry->second.c_str());
  207. ++gdmEntry;
  208. }
  209. fclose(devmapf);
  210. }
  211. */
  212. _thread = Thread::start(this);
  213. }
  214. LinuxEthernetTap::~LinuxEthernetTap()
  215. {
  216. (void)::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  217. Thread::join(_thread);
  218. ::close(_fd);
  219. ::close(_shutdownSignalPipe[0]);
  220. ::close(_shutdownSignalPipe[1]);
  221. }
  222. void LinuxEthernetTap::setEnabled(bool en)
  223. {
  224. _enabled = en;
  225. }
  226. bool LinuxEthernetTap::enabled() const
  227. {
  228. return _enabled;
  229. }
  230. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  231. {
  232. long cpid = (long)vfork();
  233. if (cpid == 0) {
  234. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  235. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  236. char iptmp[128];
  237. ::execlp("ip","ip","addr","del",ip.toString(iptmp),"dev",_dev.c_str(),(const char *)0);
  238. ::_exit(-1);
  239. } else {
  240. int exitcode = -1;
  241. ::waitpid(cpid,&exitcode,0);
  242. return (exitcode == 0);
  243. }
  244. }
  245. #ifdef __SYNOLOGY__
  246. bool LinuxEthernetTap::addIpSyn(std::vector<InetAddress> ips)
  247. {
  248. // Here we fill out interface config (ifcfg-dev) to prevent it from being killed
  249. std::string filepath = "/etc/sysconfig/network-scripts/ifcfg-"+_dev;
  250. std::string cfg_contents = "DEVICE="+_dev+"\nBOOTPROTO=static";
  251. int ip4=0,ip6=0,ip4_tot=0,ip6_tot=0;
  252. long cpid = (long)vfork();
  253. if (cpid == 0) {
  254. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  255. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  256. // We must know if there is at least (one) of each protocol version so we
  257. // can properly enumerate address/netmask combinations in the ifcfg-dev file
  258. for(int i=0; i<(int)ips.size(); i++) {
  259. if (ips[i].isV4())
  260. ip4_tot++;
  261. else
  262. ip6_tot++;
  263. }
  264. // Assemble and write contents of ifcfg-dev file
  265. for(int i=0; i<(int)ips.size(); i++) {
  266. if (ips[i].isV4()) {
  267. char iptmp[64],iptmp2[64];
  268. std::string numstr4 = ip4_tot > 1 ? std::to_string(ip4) : "";
  269. cfg_contents += "\nIPADDR"+numstr4+"="+ips[i].toIpString(iptmp)
  270. + "\nNETMASK"+numstr4+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  271. ip4++;
  272. }
  273. else {
  274. char iptmp[64],iptmp2[64];
  275. std::string numstr6 = ip6_tot > 1 ? std::to_string(ip6) : "";
  276. cfg_contents += "\nIPV6ADDR"+numstr6+"="+ips[i].toIpString(iptmp)
  277. + "\nNETMASK"+numstr6+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  278. ip6++;
  279. }
  280. }
  281. OSUtils::writeFile(filepath.c_str(), cfg_contents.c_str(), cfg_contents.length());
  282. // Finaly, add IPs
  283. for(int i=0; i<(int)ips.size(); i++){
  284. char iptmp[128],iptmp2[128];
  285. if (ips[i].isV4())
  286. ::execlp("ip","ip","addr","add",ips[i].toString(iptmp),"broadcast",ips[i].broadcast().toIpString(iptmp2),"dev",_dev.c_str(),(const char *)0);
  287. else
  288. ::execlp("ip","ip","addr","add",ips[i].toString(iptmp),"dev",_dev.c_str(),(const char *)0);
  289. }
  290. ::_exit(-1);
  291. } else if (cpid > 0) {
  292. int exitcode = -1;
  293. ::waitpid(cpid,&exitcode,0);
  294. return (exitcode == 0);
  295. }
  296. return true;
  297. }
  298. #endif // __SYNOLOGY__
  299. bool LinuxEthernetTap::addIp(const InetAddress &ip)
  300. {
  301. if (!ip)
  302. return false;
  303. std::vector<InetAddress> allIps(ips());
  304. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  305. return true;
  306. // Remove and reconfigure if address is the same but netmask is different
  307. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  308. if (i->ipsEqual(ip))
  309. ___removeIp(_dev,*i);
  310. }
  311. long cpid = (long)vfork();
  312. if (cpid == 0) {
  313. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  314. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  315. char iptmp[128],iptmp2[128];
  316. if (ip.isV4()) {
  317. ::execlp("ip","ip","addr","add",ip.toString(iptmp),"broadcast",ip.broadcast().toIpString(iptmp2),"dev",_dev.c_str(),(const char *)0);
  318. } else {
  319. ::execlp("ip","ip","addr","add",ip.toString(iptmp),"dev",_dev.c_str(),(const char *)0);
  320. }
  321. ::_exit(-1);
  322. } else if (cpid > 0) {
  323. int exitcode = -1;
  324. ::waitpid(cpid,&exitcode,0);
  325. return (exitcode == 0);
  326. }
  327. return false;
  328. }
  329. bool LinuxEthernetTap::removeIp(const InetAddress &ip)
  330. {
  331. if (!ip)
  332. return true;
  333. std::vector<InetAddress> allIps(ips());
  334. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
  335. if (___removeIp(_dev,ip))
  336. return true;
  337. }
  338. return false;
  339. }
  340. std::vector<InetAddress> LinuxEthernetTap::ips() const
  341. {
  342. struct ifaddrs *ifa = (struct ifaddrs *)0;
  343. if (getifaddrs(&ifa))
  344. return std::vector<InetAddress>();
  345. std::vector<InetAddress> r;
  346. struct ifaddrs *p = ifa;
  347. while (p) {
  348. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  349. switch(p->ifa_addr->sa_family) {
  350. case AF_INET: {
  351. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  352. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  353. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  354. } break;
  355. case AF_INET6: {
  356. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  357. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  358. uint32_t b[4];
  359. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  360. 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])));
  361. } break;
  362. }
  363. }
  364. p = p->ifa_next;
  365. }
  366. if (ifa)
  367. freeifaddrs(ifa);
  368. std::sort(r.begin(),r.end());
  369. r.erase(std::unique(r.begin(),r.end()),r.end());
  370. return r;
  371. }
  372. void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  373. {
  374. char putBuf[ZT_MAX_MTU + 64];
  375. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  376. to.copyTo(putBuf,6);
  377. from.copyTo(putBuf + 6,6);
  378. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  379. memcpy(putBuf + 14,data,len);
  380. len += 14;
  381. (void)::write(_fd,putBuf,len);
  382. }
  383. }
  384. std::string LinuxEthernetTap::deviceName() const
  385. {
  386. return _dev;
  387. }
  388. void LinuxEthernetTap::setFriendlyName(const char *friendlyName)
  389. {
  390. }
  391. void LinuxEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  392. {
  393. char *ptr,*ptr2;
  394. unsigned char mac[6];
  395. std::vector<MulticastGroup> newGroups;
  396. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  397. if (fd > 0) {
  398. char buf[131072];
  399. int n = (int)::read(fd,buf,sizeof(buf));
  400. if ((n > 0)&&(n < (int)sizeof(buf))) {
  401. buf[n] = (char)0;
  402. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  403. int fno = 0;
  404. char *devname = (char *)0;
  405. char *mcastmac = (char *)0;
  406. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  407. if (fno == 1)
  408. devname = f;
  409. else if (fno == 4)
  410. mcastmac = f;
  411. ++fno;
  412. }
  413. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  414. newGroups.push_back(MulticastGroup(MAC(mac,6),0));
  415. }
  416. }
  417. ::close(fd);
  418. }
  419. std::vector<InetAddress> allIps(ips());
  420. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  421. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  422. std::sort(newGroups.begin(),newGroups.end());
  423. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  424. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  425. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  426. added.push_back(*m);
  427. }
  428. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  429. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  430. removed.push_back(*m);
  431. }
  432. _multicastGroups.swap(newGroups);
  433. }
  434. void LinuxEthernetTap::setMtu(unsigned int mtu)
  435. {
  436. if (_mtu != mtu) {
  437. _mtu = mtu;
  438. int sock = socket(AF_INET,SOCK_DGRAM,0);
  439. if (sock > 0) {
  440. struct ifreq ifr;
  441. memset(&ifr,0,sizeof(ifr));
  442. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  443. ioctl(sock,SIOCSIFMTU,(void *)&ifr);
  444. close(sock);
  445. }
  446. }
  447. }
  448. void LinuxEthernetTap::threadMain()
  449. throw()
  450. {
  451. fd_set readfds,nullfds;
  452. MAC to,from;
  453. int n,nfds,r;
  454. char getBuf[ZT_MAX_MTU + 64];
  455. Thread::sleep(500);
  456. FD_ZERO(&readfds);
  457. FD_ZERO(&nullfds);
  458. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  459. r = 0;
  460. for(;;) {
  461. FD_SET(_shutdownSignalPipe[0],&readfds);
  462. FD_SET(_fd,&readfds);
  463. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  464. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  465. break;
  466. if (FD_ISSET(_fd,&readfds)) {
  467. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  468. if (n < 0) {
  469. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  470. break;
  471. } else {
  472. // Some tap drivers like to send the ethernet frame and the
  473. // payload in two chunks, so handle that by accumulating
  474. // data until we have at least a frame.
  475. r += n;
  476. if (r > 14) {
  477. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  478. r = _mtu + 14;
  479. if (_enabled) {
  480. to.setTo(getBuf,6);
  481. from.setTo(getBuf + 6,6);
  482. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  483. // TODO: VLAN support
  484. _handler(_arg,(void *)0,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  485. }
  486. r = 0;
  487. }
  488. }
  489. }
  490. }
  491. }
  492. } // namespace ZeroTier