LinuxEthernetTap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. uint64_t trial = 0; // incremented in the very unlikely event of a name collision with another network
  136. do {
  137. const uint64_t nwid40 = (nwid ^ (nwid >> 24)) + trial++;
  138. uint8_t tmp2[5];
  139. char tmp3[11];
  140. tmp2[0] = (uint8_t)((nwid40 >> 32) & 0xff);
  141. tmp2[1] = (uint8_t)((nwid40 >> 24) & 0xff);
  142. tmp2[2] = (uint8_t)((nwid40 >> 16) & 0xff);
  143. tmp2[3] = (uint8_t)((nwid40 >> 8) & 0xff);
  144. tmp2[4] = (uint8_t)(nwid40 & 0xff);
  145. tmp3[0] = 'z';
  146. tmp3[1] = 't';
  147. _base32_5_to_8(tmp2,tmp3 + 2);
  148. tmp3[10] = (char)0;
  149. memcpy(ifr.ifr_name,tmp3,11);
  150. OSUtils::ztsnprintf(procpath,sizeof(procpath),"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  151. } while (stat(procpath,&sbuf) == 0);
  152. #endif
  153. }
  154. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  155. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  156. ::close(_fd);
  157. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  158. }
  159. _dev = ifr.ifr_name;
  160. ::ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  161. // Open an arbitrary socket to talk to netlink
  162. int sock = socket(AF_INET,SOCK_DGRAM,0);
  163. if (sock <= 0) {
  164. ::close(_fd);
  165. throw std::runtime_error("unable to open netlink socket");
  166. }
  167. // Set MAC address
  168. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  169. mac.copyTo(ifr.ifr_ifru.ifru_hwaddr.sa_data,6);
  170. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  171. ::close(_fd);
  172. ::close(sock);
  173. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  174. return;
  175. }
  176. // Set MTU
  177. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  178. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  179. ::close(_fd);
  180. ::close(sock);
  181. throw std::runtime_error("unable to configure TAP MTU");
  182. }
  183. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  184. ::close(_fd);
  185. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  186. }
  187. /* Bring interface up */
  188. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  189. ::close(_fd);
  190. ::close(sock);
  191. throw std::runtime_error("unable to get TAP interface flags");
  192. }
  193. ifr.ifr_flags |= IFF_UP;
  194. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  195. ::close(_fd);
  196. ::close(sock);
  197. throw std::runtime_error("unable to set TAP interface flags");
  198. }
  199. ::close(sock);
  200. // Set close-on-exec so that devices cannot persist if we fork/exec for update
  201. ::fcntl(_fd,F_SETFD,fcntl(_fd,F_GETFD) | FD_CLOEXEC);
  202. (void)::pipe(_shutdownSignalPipe);
  203. /*
  204. globalDeviceMap[nwids] = _dev;
  205. devmapf = fopen((_homePath + ZT_PATH_SEPARATOR_S + "devicemap").c_str(),"w");
  206. if (devmapf) {
  207. gdmEntry = globalDeviceMap.begin();
  208. while (gdmEntry != globalDeviceMap.end()) {
  209. fprintf(devmapf,"%s=%s\n",gdmEntry->first.c_str(),gdmEntry->second.c_str());
  210. ++gdmEntry;
  211. }
  212. fclose(devmapf);
  213. }
  214. */
  215. _thread = Thread::start(this);
  216. }
  217. LinuxEthernetTap::~LinuxEthernetTap()
  218. {
  219. (void)::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  220. Thread::join(_thread);
  221. ::close(_fd);
  222. ::close(_shutdownSignalPipe[0]);
  223. ::close(_shutdownSignalPipe[1]);
  224. }
  225. void LinuxEthernetTap::setEnabled(bool en)
  226. {
  227. _enabled = en;
  228. }
  229. bool LinuxEthernetTap::enabled() const
  230. {
  231. return _enabled;
  232. }
  233. static bool ___removeIp(const std::string &_dev,const InetAddress &ip)
  234. {
  235. long cpid = (long)vfork();
  236. if (cpid == 0) {
  237. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  238. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  239. char iptmp[128];
  240. ::execlp("ip","ip","addr","del",ip.toString(iptmp),"dev",_dev.c_str(),(const char *)0);
  241. ::_exit(-1);
  242. } else {
  243. int exitcode = -1;
  244. ::waitpid(cpid,&exitcode,0);
  245. return (exitcode == 0);
  246. }
  247. }
  248. #ifdef __SYNOLOGY__
  249. bool LinuxEthernetTap::addIpSyn(std::vector<InetAddress> ips)
  250. {
  251. // Here we fill out interface config (ifcfg-dev) to prevent it from being killed
  252. std::string filepath = "/etc/sysconfig/network-scripts/ifcfg-"+_dev;
  253. std::string cfg_contents = "DEVICE="+_dev+"\nBOOTPROTO=static";
  254. int ip4=0,ip6=0,ip4_tot=0,ip6_tot=0;
  255. long cpid = (long)vfork();
  256. if (cpid == 0) {
  257. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  258. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  259. // We must know if there is at least (one) of each protocol version so we
  260. // can properly enumerate address/netmask combinations in the ifcfg-dev file
  261. for(int i=0; i<(int)ips.size(); i++) {
  262. if (ips[i].isV4())
  263. ip4_tot++;
  264. else
  265. ip6_tot++;
  266. }
  267. // Assemble and write contents of ifcfg-dev file
  268. for(int i=0; i<(int)ips.size(); i++) {
  269. if (ips[i].isV4()) {
  270. char iptmp[64],iptmp2[64];
  271. std::string numstr4 = ip4_tot > 1 ? std::to_string(ip4) : "";
  272. cfg_contents += "\nIPADDR"+numstr4+"="+ips[i].toIpString(iptmp)
  273. + "\nNETMASK"+numstr4+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  274. ip4++;
  275. }
  276. else {
  277. char iptmp[64],iptmp2[64];
  278. std::string numstr6 = ip6_tot > 1 ? std::to_string(ip6) : "";
  279. cfg_contents += "\nIPV6ADDR"+numstr6+"="+ips[i].toIpString(iptmp)
  280. + "\nNETMASK"+numstr6+"="+ips[i].netmask().toIpString(iptmp2)+"\n";
  281. ip6++;
  282. }
  283. }
  284. OSUtils::writeFile(filepath.c_str(), cfg_contents.c_str(), cfg_contents.length());
  285. // Finaly, add IPs
  286. for(int i=0; i<(int)ips.size(); i++){
  287. char iptmp[128],iptmp2[128];
  288. if (ips[i].isV4())
  289. ::execlp("ip","ip","addr","add",ips[i].toString(iptmp),"broadcast",ips[i].broadcast().toIpString(iptmp2),"dev",_dev.c_str(),(const char *)0);
  290. else
  291. ::execlp("ip","ip","addr","add",ips[i].toString(iptmp),"dev",_dev.c_str(),(const char *)0);
  292. }
  293. ::_exit(-1);
  294. } else if (cpid > 0) {
  295. int exitcode = -1;
  296. ::waitpid(cpid,&exitcode,0);
  297. return (exitcode == 0);
  298. }
  299. return true;
  300. }
  301. #endif // __SYNOLOGY__
  302. bool LinuxEthernetTap::addIp(const InetAddress &ip)
  303. {
  304. if (!ip)
  305. return false;
  306. std::vector<InetAddress> allIps(ips());
  307. if (std::binary_search(allIps.begin(),allIps.end(),ip))
  308. return true;
  309. // Remove and reconfigure if address is the same but netmask is different
  310. for(std::vector<InetAddress>::iterator i(allIps.begin());i!=allIps.end();++i) {
  311. if (i->ipsEqual(ip))
  312. ___removeIp(_dev,*i);
  313. }
  314. long cpid = (long)vfork();
  315. if (cpid == 0) {
  316. OSUtils::redirectUnixOutputs("/dev/null",(const char *)0);
  317. setenv("PATH", "/sbin:/bin:/usr/sbin:/usr/bin", 1);
  318. char iptmp[128],iptmp2[128];
  319. if (ip.isV4()) {
  320. ::execlp("ip","ip","addr","add",ip.toString(iptmp),"broadcast",ip.broadcast().toIpString(iptmp2),"dev",_dev.c_str(),(const char *)0);
  321. } else {
  322. ::execlp("ip","ip","addr","add",ip.toString(iptmp),"dev",_dev.c_str(),(const char *)0);
  323. }
  324. ::_exit(-1);
  325. } else if (cpid > 0) {
  326. int exitcode = -1;
  327. ::waitpid(cpid,&exitcode,0);
  328. return (exitcode == 0);
  329. }
  330. return false;
  331. }
  332. bool LinuxEthernetTap::removeIp(const InetAddress &ip)
  333. {
  334. if (!ip)
  335. return true;
  336. std::vector<InetAddress> allIps(ips());
  337. if (std::find(allIps.begin(),allIps.end(),ip) != allIps.end()) {
  338. if (___removeIp(_dev,ip))
  339. return true;
  340. }
  341. return false;
  342. }
  343. std::vector<InetAddress> LinuxEthernetTap::ips() const
  344. {
  345. struct ifaddrs *ifa = (struct ifaddrs *)0;
  346. if (getifaddrs(&ifa))
  347. return std::vector<InetAddress>();
  348. std::vector<InetAddress> r;
  349. struct ifaddrs *p = ifa;
  350. while (p) {
  351. if ((!strcmp(p->ifa_name,_dev.c_str()))&&(p->ifa_addr)&&(p->ifa_netmask)&&(p->ifa_addr->sa_family == p->ifa_netmask->sa_family)) {
  352. switch(p->ifa_addr->sa_family) {
  353. case AF_INET: {
  354. struct sockaddr_in *sin = (struct sockaddr_in *)p->ifa_addr;
  355. struct sockaddr_in *nm = (struct sockaddr_in *)p->ifa_netmask;
  356. r.push_back(InetAddress(&(sin->sin_addr.s_addr),4,Utils::countBits((uint32_t)nm->sin_addr.s_addr)));
  357. } break;
  358. case AF_INET6: {
  359. struct sockaddr_in6 *sin = (struct sockaddr_in6 *)p->ifa_addr;
  360. struct sockaddr_in6 *nm = (struct sockaddr_in6 *)p->ifa_netmask;
  361. uint32_t b[4];
  362. memcpy(b,nm->sin6_addr.s6_addr,sizeof(b));
  363. 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])));
  364. } break;
  365. }
  366. }
  367. p = p->ifa_next;
  368. }
  369. if (ifa)
  370. freeifaddrs(ifa);
  371. std::sort(r.begin(),r.end());
  372. r.erase(std::unique(r.begin(),r.end()),r.end());
  373. return r;
  374. }
  375. void LinuxEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  376. {
  377. char putBuf[ZT_MAX_MTU + 64];
  378. if ((_fd > 0)&&(len <= _mtu)&&(_enabled)) {
  379. to.copyTo(putBuf,6);
  380. from.copyTo(putBuf + 6,6);
  381. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  382. memcpy(putBuf + 14,data,len);
  383. len += 14;
  384. (void)::write(_fd,putBuf,len);
  385. }
  386. }
  387. std::string LinuxEthernetTap::deviceName() const
  388. {
  389. return _dev;
  390. }
  391. void LinuxEthernetTap::setFriendlyName(const char *friendlyName)
  392. {
  393. }
  394. void LinuxEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  395. {
  396. char *ptr,*ptr2;
  397. unsigned char mac[6];
  398. std::vector<MulticastGroup> newGroups;
  399. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  400. if (fd > 0) {
  401. char buf[131072];
  402. int n = (int)::read(fd,buf,sizeof(buf));
  403. if ((n > 0)&&(n < (int)sizeof(buf))) {
  404. buf[n] = (char)0;
  405. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  406. int fno = 0;
  407. char *devname = (char *)0;
  408. char *mcastmac = (char *)0;
  409. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  410. if (fno == 1)
  411. devname = f;
  412. else if (fno == 4)
  413. mcastmac = f;
  414. ++fno;
  415. }
  416. if ((devname)&&(!strcmp(devname,_dev.c_str()))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  417. newGroups.push_back(MulticastGroup(MAC(mac,6),0));
  418. }
  419. }
  420. ::close(fd);
  421. }
  422. std::vector<InetAddress> allIps(ips());
  423. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  424. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  425. std::sort(newGroups.begin(),newGroups.end());
  426. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  427. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  428. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  429. added.push_back(*m);
  430. }
  431. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  432. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  433. removed.push_back(*m);
  434. }
  435. _multicastGroups.swap(newGroups);
  436. }
  437. void LinuxEthernetTap::setMtu(unsigned int mtu)
  438. {
  439. if (_mtu != mtu) {
  440. _mtu = mtu;
  441. int sock = socket(AF_INET,SOCK_DGRAM,0);
  442. if (sock > 0) {
  443. struct ifreq ifr;
  444. memset(&ifr,0,sizeof(ifr));
  445. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  446. ioctl(sock,SIOCSIFMTU,(void *)&ifr);
  447. close(sock);
  448. }
  449. }
  450. }
  451. void LinuxEthernetTap::threadMain()
  452. throw()
  453. {
  454. fd_set readfds,nullfds;
  455. MAC to,from;
  456. int n,nfds,r;
  457. char getBuf[ZT_MAX_MTU + 64];
  458. Thread::sleep(500);
  459. FD_ZERO(&readfds);
  460. FD_ZERO(&nullfds);
  461. nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  462. r = 0;
  463. for(;;) {
  464. FD_SET(_shutdownSignalPipe[0],&readfds);
  465. FD_SET(_fd,&readfds);
  466. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  467. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  468. break;
  469. if (FD_ISSET(_fd,&readfds)) {
  470. n = (int)::read(_fd,getBuf + r,sizeof(getBuf) - r);
  471. if (n < 0) {
  472. if ((errno != EINTR)&&(errno != ETIMEDOUT))
  473. break;
  474. } else {
  475. // Some tap drivers like to send the ethernet frame and the
  476. // payload in two chunks, so handle that by accumulating
  477. // data until we have at least a frame.
  478. r += n;
  479. if (r > 14) {
  480. if (r > ((int)_mtu + 14)) // sanity check for weird TAP behavior on some platforms
  481. r = _mtu + 14;
  482. if (_enabled) {
  483. to.setTo(getBuf,6);
  484. from.setTo(getBuf + 6,6);
  485. unsigned int etherType = ntohs(((const uint16_t *)getBuf)[6]);
  486. // TODO: VLAN support
  487. _handler(_arg,(void *)0,_nwid,from,to,etherType,0,(const void *)(getBuf + 14),r - 14);
  488. }
  489. r = 0;
  490. }
  491. }
  492. }
  493. }
  494. }
  495. } // namespace ZeroTier