EthernetTap.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2012-2013 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 <iostream>
  28. #include <string>
  29. #include "EthernetTap.hpp"
  30. #include "Logger.hpp"
  31. #include "RuntimeEnvironment.hpp"
  32. #include "Mutex.hpp"
  33. #include "MulticastGroup.hpp"
  34. // ff:ff:ff:ff:ff:ff with no ADI
  35. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  36. /* ======================================================================== */
  37. #if defined(__linux__) || defined(linux) || defined(__LINUX__) || defined(__linux)
  38. /* ======================================================================== */
  39. #include <stdint.h>
  40. #include <stdio.h>
  41. #include <stdlib.h>
  42. #include <string.h>
  43. #include <unistd.h>
  44. #include <signal.h>
  45. #include <fcntl.h>
  46. #include <errno.h>
  47. #include <sys/types.h>
  48. #include <sys/stat.h>
  49. #include <sys/ioctl.h>
  50. #include <sys/wait.h>
  51. #include <netinet/in.h>
  52. #include <net/if_arp.h>
  53. #include <arpa/inet.h>
  54. #include <linux/if.h>
  55. #include <linux/if_tun.h>
  56. #include <linux/if_addr.h>
  57. #include <linux/if_ether.h>
  58. #define ZT_ETHERTAP_IP_COMMAND "/sbin/ip"
  59. #define ZT_ETHERTAP_SYSCTL_COMMAND "/sbin/sysctl"
  60. namespace ZeroTier {
  61. static Mutex __tapCreateLock;
  62. EthernetTap::EthernetTap(const RuntimeEnvironment *renv,const MAC &mac,unsigned int mtu)
  63. throw(std::runtime_error) :
  64. _mac(mac),
  65. _mtu(mtu),
  66. _r(renv),
  67. _putBuf((unsigned char *)0),
  68. _getBuf((unsigned char *)0),
  69. _fd(0),
  70. _isReading(false)
  71. {
  72. char procpath[128];
  73. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  74. _fd = ::open("/dev/net/tun",O_RDWR);
  75. if (_fd <= 0)
  76. throw std::runtime_error("could not open TUN/TAP device");
  77. struct ifreq ifr;
  78. memset(&ifr,0,sizeof(ifr));
  79. { // pick an unused device name
  80. int devno = 0;
  81. struct stat sbuf;
  82. do {
  83. sprintf(ifr.ifr_name,"zt%d",devno++);
  84. sprintf(procpath,"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  85. } while (stat(procpath,&sbuf) == 0);
  86. }
  87. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  88. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  89. ::close(_fd);
  90. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  91. }
  92. strcpy(_dev,ifr.ifr_name);
  93. ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  94. // Open an arbitrary socket to talk to netlink
  95. int sock = socket(AF_INET,SOCK_DGRAM,0);
  96. if (sock <= 0) {
  97. ::close(_fd);
  98. throw std::runtime_error("unable to open netlink socket");
  99. }
  100. // Set MAC address
  101. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  102. memcpy(ifr.ifr_ifru.ifru_hwaddr.sa_data,mac.data,6);
  103. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  104. ::close(_fd);
  105. ::close(sock);
  106. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  107. return;
  108. }
  109. // Set MTU
  110. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  111. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  112. ::close(_fd);
  113. ::close(sock);
  114. throw std::runtime_error("unable to configure TAP MTU");
  115. }
  116. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  117. ::close(_fd);
  118. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  119. }
  120. /* Bring interface up */
  121. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  122. ::close(_fd);
  123. ::close(sock);
  124. throw std::runtime_error("unable to get TAP interface flags");
  125. }
  126. ifr.ifr_flags |= IFF_UP;
  127. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  128. ::close(_fd);
  129. ::close(sock);
  130. throw std::runtime_error("unable to set TAP interface flags");
  131. }
  132. ::close(sock);
  133. _putBuf = new unsigned char[((mtu + 16) * 2)];
  134. _getBuf = _putBuf + (mtu + 16);
  135. TRACE("tap %s created",_dev);
  136. }
  137. EthernetTap::~EthernetTap()
  138. {
  139. this->close();
  140. delete [] _putBuf;
  141. }
  142. static bool ___removeIp(const char *_dev,std::set<InetAddress> &_ips,const InetAddress &ip)
  143. {
  144. long cpid;
  145. if ((cpid = (long)fork()) == 0) {
  146. execl(ZT_ETHERTAP_IP_COMMAND,ZT_ETHERTAP_IP_COMMAND,"addr","del",ip.toString().c_str(),"dev",_dev,(const char *)0);
  147. exit(1); /* not reached unless exec fails */
  148. } else {
  149. int exitcode = 1;
  150. waitpid(cpid,&exitcode,0);
  151. if (exitcode == 0) {
  152. _ips.erase(ip);
  153. return true;
  154. } else return false;
  155. }
  156. }
  157. bool EthernetTap::addIP(const InetAddress &ip)
  158. {
  159. Mutex::Lock _l(_ips_m);
  160. if (!ip)
  161. return false;
  162. if (_ips.count(ip) > 0)
  163. return true;
  164. // Remove and reconfigure if address is the same but netmask is different
  165. for(std::set<InetAddress>::iterator i(_ips.begin());i!=_ips.end();++i) {
  166. if (i->ipsEqual(ip)) {
  167. ___removeIp(_dev,_ips,*i);
  168. break;
  169. }
  170. }
  171. int cpid;
  172. if ((cpid = (int)fork()) == 0) {
  173. execl(ZT_ETHERTAP_IP_COMMAND,ZT_ETHERTAP_IP_COMMAND,"addr","add",ip.toString().c_str(),"dev",_dev,(const char *)0);
  174. exit(-1);
  175. } else {
  176. int exitcode = -1;
  177. waitpid(cpid,&exitcode,0);
  178. if (exitcode == 0) {
  179. _ips.insert(ip);
  180. return true;
  181. } else return false;
  182. }
  183. return false;
  184. }
  185. bool EthernetTap::removeIP(const InetAddress &ip)
  186. {
  187. Mutex::Lock _l(_ips_m);
  188. if (_ips.count(ip) > 0)
  189. return ___removeIp(_dev,_ips,ip);
  190. return false;
  191. }
  192. void EthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  193. {
  194. if ((_fd > 0)&&(len <= _mtu)) {
  195. for(int i=0;i<6;++i)
  196. _putBuf[i] = to.data[i];
  197. for(int i=0;i<6;++i)
  198. _putBuf[i+6] = from.data[i];
  199. *((uint16_t *)(_putBuf + 12)) = htons((uint16_t)etherType);
  200. memcpy(_putBuf + 14,data,len);
  201. ::write(_fd,_putBuf,len + 14);
  202. }
  203. }
  204. unsigned int EthernetTap::get(MAC &from,MAC &to,unsigned int &etherType,void *buf)
  205. {
  206. for(;;) {
  207. if (_fd > 0) {
  208. _isReading_m.lock();
  209. _isReading = true;
  210. _isReadingThreadId = pthread_self();
  211. _isReading_m.unlock();
  212. int n = (int)::read(_fd,_getBuf,_mtu + 14);
  213. _isReading_m.lock();
  214. _isReading = false;
  215. _isReading_m.unlock();
  216. if (n > 14) {
  217. for(int i=0;i<6;++i)
  218. to.data[i] = _getBuf[i];
  219. for(int i=0;i<6;++i)
  220. from.data[i] = _getBuf[i + 6];
  221. etherType = ntohs(((uint16_t *)_getBuf)[6]);
  222. n -= 14;
  223. memcpy(buf,_getBuf + 14,n);
  224. return (unsigned int)n;
  225. } else if (n < 0) {
  226. if (_fd <= 0)
  227. break;
  228. else if ((errno == EINTR)||(errno == ETIMEDOUT))
  229. continue;
  230. else {
  231. TRACE("unexpected error reading from tap: %s",strerror(errno));
  232. ::close(_fd);
  233. _fd = 0;
  234. break;
  235. }
  236. } else {
  237. TRACE("incomplete read from tap: %d bytes",n);
  238. continue;
  239. }
  240. }
  241. }
  242. return 0;
  243. }
  244. std::string EthernetTap::deviceName()
  245. {
  246. return std::string(_dev);
  247. }
  248. bool EthernetTap::open() const
  249. {
  250. return (_fd > 0);
  251. }
  252. void EthernetTap::close()
  253. {
  254. Mutex::Lock _l(__tapCreateLock); // also prevent create during close()
  255. if (_fd > 0) {
  256. int f = _fd;
  257. _fd = 0;
  258. ::close(f);
  259. _isReading_m.lock();
  260. if (_isReading)
  261. pthread_kill(_isReadingThreadId,SIGUSR2);
  262. _isReading_m.unlock();
  263. }
  264. }
  265. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  266. {
  267. char *ptr,*ptr2;
  268. unsigned char mac[6];
  269. std::set<MulticastGroup> newGroups;
  270. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  271. if (fd > 0) {
  272. char buf[131072];
  273. int n = (int)::read(fd,buf,sizeof(buf));
  274. if ((n > 0)&&(n < (int)sizeof(buf))) {
  275. buf[n] = (char)0;
  276. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  277. int fno = 0;
  278. char *devname = (char *)0;
  279. char *mcastmac = (char *)0;
  280. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  281. if (fno == 1)
  282. devname = f;
  283. else if (fno == 4)
  284. mcastmac = f;
  285. ++fno;
  286. }
  287. if ((devname)&&(!strcmp(devname,_dev))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  288. newGroups.insert(MulticastGroup(MAC(mac),0));
  289. }
  290. }
  291. ::close(fd);
  292. }
  293. {
  294. Mutex::Lock _l(_ips_m);
  295. for(std::set<InetAddress>::const_iterator i(_ips.begin());i!=_ips.end();++i)
  296. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  297. }
  298. bool changed = false;
  299. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  300. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  301. if (!groups.count(*mg)) {
  302. groups.insert(*mg);
  303. changed = true;
  304. }
  305. }
  306. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  307. if (!newGroups.count(*mg)) {
  308. groups.erase(mg++);
  309. changed = true;
  310. } else ++mg;
  311. }
  312. return changed;
  313. }
  314. } // namespace ZeroTier
  315. /* ======================================================================== */
  316. #elif defined(__APPLE__) /* ----------------------------------------------- */
  317. /* ======================================================================== */
  318. #include <stdint.h>
  319. #include <stdio.h>
  320. #include <stdlib.h>
  321. #include <string.h>
  322. #include <unistd.h>
  323. #include <signal.h>
  324. #include <fcntl.h>
  325. #include <errno.h>
  326. #include <sys/types.h>
  327. #include <sys/stat.h>
  328. #include <sys/ioctl.h>
  329. #include <sys/uio.h>
  330. #include <sys/param.h>
  331. #include <sys/sysctl.h>
  332. #include <netinet/in.h>
  333. #include <arpa/inet.h>
  334. #include <net/route.h>
  335. #include <net/if_dl.h>
  336. #include <ifaddrs.h>
  337. #define ZT_ETHERTAP_IFCONFIG "/sbin/ifconfig"
  338. #define ZT_MAC_KEXTLOAD "/sbin/kextload"
  339. #define ZT_MAC_IPCONFIG "/usr/sbin/ipconfig"
  340. namespace ZeroTier {
  341. static Mutex __tapCreateLock;
  342. EthernetTap::EthernetTap(const RuntimeEnvironment *renv,const MAC &mac,unsigned int mtu)
  343. throw(std::runtime_error) :
  344. _mac(mac),
  345. _mtu(mtu),
  346. _r(renv),
  347. _putBuf((unsigned char *)0),
  348. _getBuf((unsigned char *)0),
  349. _fd(0),
  350. _isReading(false)
  351. {
  352. char devpath[64],ethaddr[64],mtustr[16];
  353. struct stat tmp;
  354. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  355. // Check for existence of ZT tap devices, try to load module if not there
  356. if (stat("/dev/zt0",&tmp)) {
  357. int kextpid;
  358. char tmp[4096];
  359. strcpy(tmp,_r->homePath.c_str());
  360. if ((kextpid = (int)fork()) == 0) {
  361. chdir(tmp);
  362. execl(ZT_MAC_KEXTLOAD,ZT_MAC_KEXTLOAD,"-q","-repository",tmp,"tap.kext",(const char *)0);
  363. exit(-1);
  364. } else {
  365. int exitcode = -1;
  366. waitpid(kextpid,&exitcode,0);
  367. usleep(500);
  368. }
  369. }
  370. if (stat("/dev/zt0",&tmp))
  371. throw std::runtime_error("/dev/zt# tap devices do not exist and unable to load kernel extension");
  372. // Open the first available device (ones in use will fail with resource busy)
  373. for(int i=0;i<256;++i) {
  374. sprintf(devpath,"/dev/zt%d",i);
  375. if (stat(devpath,&tmp))
  376. throw std::runtime_error("no more TAP devices available");
  377. _fd = ::open(devpath,O_RDWR);
  378. if (_fd > 0) {
  379. sprintf(_dev,"zt%d",i);
  380. break;
  381. }
  382. }
  383. if (_fd <= 0)
  384. throw std::runtime_error("unable to open TAP device or no more devices available");
  385. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  386. ::close(_fd);
  387. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  388. }
  389. sprintf(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]);
  390. sprintf(mtustr,"%u",mtu);
  391. // Configure MAC address and MTU, bring interface up
  392. int cpid;
  393. if ((cpid = (int)fork()) == 0) {
  394. execl(ZT_ETHERTAP_IFCONFIG,ZT_ETHERTAP_IFCONFIG,_dev,"lladdr",ethaddr,"mtu",mtustr,"up",(const char *)0);
  395. exit(-1);
  396. } else {
  397. int exitcode = -1;
  398. waitpid(cpid,&exitcode,0);
  399. if (exitcode) {
  400. ::close(_fd);
  401. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  402. }
  403. }
  404. // OSX seems to require that IPv6 be turned on on tap devices
  405. if ((cpid = (int)fork()) == 0) {
  406. execl(ZT_MAC_IPCONFIG,ZT_MAC_IPCONFIG,"set",_dev,"AUTOMATIC-V6",(const char *)0);
  407. exit(-1);
  408. } else {
  409. int exitcode = -1;
  410. waitpid(cpid,&exitcode,0);
  411. if (exitcode) {
  412. ::close(_fd);
  413. throw std::runtime_error("ipconfig failure enabling IPv6 link-local addressing");
  414. }
  415. }
  416. _putBuf = new unsigned char[((mtu + 14) * 2)];
  417. _getBuf = _putBuf + (mtu + 14);
  418. }
  419. EthernetTap::~EthernetTap()
  420. {
  421. this->close();
  422. delete [] _putBuf;
  423. }
  424. // Helper function to actually remove IP from network device, execs ifconfig
  425. static bool ___removeIp(const char *_dev,const InetAddress &ip)
  426. {
  427. int cpid;
  428. if ((cpid = (int)fork()) == 0) {
  429. execl(ZT_ETHERTAP_IFCONFIG,ZT_ETHERTAP_IFCONFIG,_dev,"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  430. exit(-1);
  431. } else {
  432. int exitcode = -1;
  433. waitpid(cpid,&exitcode,0);
  434. return (exitcode == 0);
  435. }
  436. return false; // never reached, make compiler shut up about return value
  437. }
  438. bool EthernetTap::addIP(const InetAddress &ip)
  439. {
  440. Mutex::Lock _l(_ips_m);
  441. if (!ip)
  442. return false;
  443. if (_ips.count(ip) > 0)
  444. return true; // IP/netmask already assigned
  445. // Remove and reconfigure if address is the same but netmask is different
  446. for(std::set<InetAddress>::iterator i(_ips.begin());i!=_ips.end();++i) {
  447. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  448. if (___removeIp(_dev,*i)) {
  449. _ips.erase(i);
  450. break;
  451. } else {
  452. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  453. }
  454. }
  455. }
  456. int cpid;
  457. if ((cpid = (int)fork()) == 0) {
  458. execl(ZT_ETHERTAP_IFCONFIG,ZT_ETHERTAP_IFCONFIG,_dev,ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  459. exit(-1);
  460. } else {
  461. int exitcode = -1;
  462. waitpid(cpid,&exitcode,0);
  463. if (exitcode == 0) {
  464. _ips.insert(ip);
  465. return true;
  466. }
  467. }
  468. return false;
  469. }
  470. bool EthernetTap::removeIP(const InetAddress &ip)
  471. {
  472. Mutex::Lock _l(_ips_m);
  473. if (_ips.count(ip) > 0) {
  474. if (___removeIp(_dev,ip)) {
  475. _ips.erase(ip);
  476. return true;
  477. }
  478. }
  479. return false;
  480. }
  481. void EthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  482. {
  483. if ((_fd > 0)&&(len <= _mtu)) {
  484. for(int i=0;i<6;++i)
  485. _putBuf[i] = to.data[i];
  486. for(int i=0;i<6;++i)
  487. _putBuf[i+6] = from.data[i];
  488. *((uint16_t *)(_putBuf + 12)) = htons((uint16_t)etherType);
  489. memcpy(_putBuf + 14,data,len);
  490. len += 14;
  491. int n = (int)::write(_fd,_putBuf,len);
  492. if (n <= 0) {
  493. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  494. } else if (n != (int)len) {
  495. // Saw this gremlin once, so log it if we see it again... OSX tap
  496. // or something seems to have goofy issues with certain MTUs.
  497. LOG("WARNING: Apple gremlin: tap write() wrote %d of %u bytes of frame",n,len);
  498. }
  499. }
  500. }
  501. unsigned int EthernetTap::get(MAC &from,MAC &to,unsigned int &etherType,void *buf)
  502. {
  503. for(;;) {
  504. if (_fd > 0) {
  505. _isReading_m.lock();
  506. _isReading = true;
  507. _isReadingThreadId = pthread_self();
  508. _isReading_m.unlock();
  509. int n = (int)::read(_fd,_getBuf,_mtu + 14);
  510. _isReading_m.lock();
  511. _isReading = false;
  512. _isReading_m.unlock();
  513. if (n > 14) {
  514. for(int i=0;i<6;++i)
  515. to.data[i] = _getBuf[i];
  516. for(int i=0;i<6;++i)
  517. from.data[i] = _getBuf[i + 6];
  518. etherType = ntohs(((uint16_t *)_getBuf)[6]);
  519. n -= 14;
  520. memcpy(buf,_getBuf + 14,n);
  521. return (unsigned int)n;
  522. } else if (n < 0) {
  523. if (_fd <= 0)
  524. break;
  525. else if ((errno == EINTR)||(errno == ETIMEDOUT))
  526. continue;
  527. else {
  528. TRACE("unexpected error reading from tap: %s",strerror(errno));
  529. ::close(_fd);
  530. _fd = 0;
  531. break;
  532. }
  533. } else {
  534. TRACE("incomplete read from tap: %d bytes",n);
  535. continue;
  536. }
  537. }
  538. }
  539. return 0;
  540. }
  541. std::string EthernetTap::deviceName()
  542. {
  543. return std::string(_dev);
  544. }
  545. bool EthernetTap::open() const
  546. {
  547. return (_fd > 0);
  548. }
  549. void EthernetTap::close()
  550. {
  551. Mutex::Lock _l(__tapCreateLock); // also prevent create during close()
  552. if (_fd > 0) {
  553. int f = _fd;
  554. _fd = 0;
  555. ::close(f);
  556. _isReading_m.lock();
  557. if (_isReading)
  558. pthread_kill(_isReadingThreadId,SIGUSR2);
  559. _isReading_m.unlock();
  560. }
  561. }
  562. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  563. {
  564. std::set<MulticastGroup> newGroups;
  565. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  566. if (!getifmaddrs(&ifmap)) {
  567. struct ifmaddrs *p = ifmap;
  568. while (p) {
  569. if (p->ifma_addr->sa_family == AF_LINK) {
  570. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  571. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  572. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= sizeof(_dev))&&(!memcmp(_dev,in->sdl_data,in->sdl_nlen)))
  573. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen),0));
  574. }
  575. p = p->ifma_next;
  576. }
  577. freeifmaddrs(ifmap);
  578. }
  579. {
  580. Mutex::Lock _l(_ips_m);
  581. for(std::set<InetAddress>::const_iterator i(_ips.begin());i!=_ips.end();++i)
  582. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  583. }
  584. bool changed = false;
  585. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  586. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  587. if (!groups.count(*mg)) {
  588. groups.insert(*mg);
  589. changed = true;
  590. }
  591. }
  592. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  593. if (!newGroups.count(*mg)) {
  594. groups.erase(mg++);
  595. changed = true;
  596. } else ++mg;
  597. }
  598. return changed;
  599. }
  600. } // namespace ZeroTier
  601. /* ======================================================================== */
  602. #elif defined(_WIN32) /* -------------------------------------------------- */
  603. /* ======================================================================== */
  604. /* ======================================================================== */
  605. #endif
  606. /* ======================================================================== */