EthernetTap.cpp 18 KB

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