EthernetTap.cpp 18 KB

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