EthernetTap.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  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 <set>
  30. #include <algorithm>
  31. #include "Constants.hpp"
  32. #include "EthernetTap.hpp"
  33. #include "Logger.hpp"
  34. #include "RuntimeEnvironment.hpp"
  35. #include "Utils.hpp"
  36. #include "Mutex.hpp"
  37. // ff:ff:ff:ff:ff:ff with no ADI
  38. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  39. //
  40. // TAP implementation for *nix OSes, with some specialization for different flavors
  41. //
  42. #ifdef __UNIX_LIKE__ /////////////////////////////////////////////////////////
  43. #include <stdint.h>
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46. #include <string.h>
  47. #include <unistd.h>
  48. #include <signal.h>
  49. #include <fcntl.h>
  50. #include <errno.h>
  51. #include <sys/types.h>
  52. #include <sys/stat.h>
  53. #include <sys/ioctl.h>
  54. #include <sys/wait.h>
  55. #include <sys/select.h>
  56. #include <netinet/in.h>
  57. #include <net/if_arp.h>
  58. #include <arpa/inet.h>
  59. // Command identifiers used with command finder static (on various *nixes)
  60. #define ZT_UNIX_IP_COMMAND 1
  61. #define ZT_UNIX_IFCONFIG_COMMAND 2
  62. #define ZT_MAC_KEXTLOAD_COMMAND 3
  63. #define ZT_MAC_IPCONFIG_COMMAND 4
  64. // Finds external commands on startup
  65. class _CommandFinder
  66. {
  67. public:
  68. _CommandFinder()
  69. {
  70. _findCmd(ZT_UNIX_IFCONFIG_COMMAND,"ifconfig");
  71. #ifdef __LINUX__
  72. _findCmd(ZT_UNIX_IP_COMMAND,"ip");
  73. #endif
  74. #ifdef __APPLE__
  75. _findCmd(ZT_MAC_KEXTLOAD_COMMAND,"kextload");
  76. _findCmd(ZT_MAC_IPCONFIG_COMMAND,"ipconfig");
  77. #endif
  78. }
  79. // returns NULL if command was not found
  80. inline const char *operator[](int id) const
  81. throw()
  82. {
  83. std::map<int,std::string>::const_iterator c(_paths.find(id));
  84. if (c == _paths.end())
  85. return (const char *)0;
  86. return c->second.c_str();
  87. }
  88. private:
  89. inline void _findCmd(int id,const char *name)
  90. {
  91. char tmp[4096];
  92. sprintf(tmp,"/sbin/%s",name);
  93. if (ZeroTier::Utils::fileExists(tmp)) {
  94. _paths[id] = tmp;
  95. return;
  96. }
  97. sprintf(tmp,"/usr/sbin/%s",name);
  98. if (ZeroTier::Utils::fileExists(tmp)) {
  99. _paths[id] = tmp;
  100. return;
  101. }
  102. sprintf(tmp,"/bin/%s",name);
  103. if (ZeroTier::Utils::fileExists(tmp)) {
  104. _paths[id] = tmp;
  105. return;
  106. }
  107. sprintf(tmp,"/usr/bin/%s",name);
  108. if (ZeroTier::Utils::fileExists(tmp)) {
  109. _paths[id] = tmp;
  110. return;
  111. }
  112. }
  113. std::map<int,std::string> _paths;
  114. };
  115. static const _CommandFinder UNIX_COMMANDS;
  116. #ifdef __LINUX__
  117. #include <linux/if.h>
  118. #include <linux/if_tun.h>
  119. #include <linux/if_addr.h>
  120. #include <linux/if_ether.h>
  121. #endif // __LINUX__
  122. #ifdef __APPLE__
  123. #include <sys/uio.h>
  124. #include <sys/param.h>
  125. #include <sys/sysctl.h>
  126. #include <net/route.h>
  127. #include <net/if_dl.h>
  128. #include <ifaddrs.h>
  129. #endif // __APPLE__
  130. namespace ZeroTier {
  131. // Only permit one tap to be opened concurrently across the entire process
  132. static Mutex __tapCreateLock;
  133. #ifdef __LINUX__
  134. EthernetTap::EthernetTap(
  135. const RuntimeEnvironment *renv,
  136. const char *tag,
  137. const MAC &mac,
  138. unsigned int mtu,
  139. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  140. void *arg)
  141. throw(std::runtime_error) :
  142. _mac(mac),
  143. _mtu(mtu),
  144. _r(renv),
  145. _handler(handler),
  146. _arg(arg),
  147. _fd(0)
  148. {
  149. char procpath[128];
  150. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  151. if (mtu > 4096)
  152. throw std::runtime_error("max tap MTU is 4096");
  153. _fd = ::open("/dev/net/tun",O_RDWR);
  154. if (_fd <= 0)
  155. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  156. struct ifreq ifr;
  157. memset(&ifr,0,sizeof(ifr));
  158. { // pick an unused device name
  159. int devno = 0;
  160. struct stat sbuf;
  161. do {
  162. sprintf(ifr.ifr_name,"zt%d",devno++);
  163. sprintf(procpath,"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  164. } while (stat(procpath,&sbuf) == 0);
  165. }
  166. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  167. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  168. ::close(_fd);
  169. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  170. }
  171. strcpy(_dev,ifr.ifr_name);
  172. ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  173. // Open an arbitrary socket to talk to netlink
  174. int sock = socket(AF_INET,SOCK_DGRAM,0);
  175. if (sock <= 0) {
  176. ::close(_fd);
  177. throw std::runtime_error("unable to open netlink socket");
  178. }
  179. // Set MAC address
  180. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  181. memcpy(ifr.ifr_ifru.ifru_hwaddr.sa_data,mac.data,6);
  182. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  183. ::close(_fd);
  184. ::close(sock);
  185. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  186. return;
  187. }
  188. // Set MTU
  189. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  190. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  191. ::close(_fd);
  192. ::close(sock);
  193. throw std::runtime_error("unable to configure TAP MTU");
  194. }
  195. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  196. ::close(_fd);
  197. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  198. }
  199. /* Bring interface up */
  200. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  201. ::close(_fd);
  202. ::close(sock);
  203. throw std::runtime_error("unable to get TAP interface flags");
  204. }
  205. ifr.ifr_flags |= IFF_UP;
  206. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  207. ::close(_fd);
  208. ::close(sock);
  209. throw std::runtime_error("unable to set TAP interface flags");
  210. }
  211. ::close(sock);
  212. ::pipe(_shutdownSignalPipe);
  213. TRACE("tap %s created",_dev);
  214. _thread = Thread::start(this);
  215. }
  216. #endif // __LINUX__
  217. #ifdef __APPLE__
  218. EthernetTap::EthernetTap(
  219. const RuntimeEnvironment *renv,
  220. const char *tag,
  221. const MAC &mac,
  222. unsigned int mtu,
  223. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  224. void *arg)
  225. throw(std::runtime_error) :
  226. _mac(mac),
  227. _mtu(mtu),
  228. _r(renv),
  229. _handler(handler),
  230. _arg(arg),
  231. _fd(0)
  232. {
  233. char devpath[64],ethaddr[64],mtustr[16];
  234. struct stat tmp;
  235. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  236. if (mtu > 4096)
  237. throw std::runtime_error("max tap MTU is 4096");
  238. // Check for existence of ZT tap devices, try to load module if not there
  239. const char *kextload = UNIX_COMMANDS[ZT_MAC_KEXTLOAD_COMMAND];
  240. if ((stat("/dev/zt0",&tmp))&&(kextload)) {
  241. long kextpid;
  242. char tmp[4096];
  243. strcpy(tmp,_r->homePath.c_str());
  244. if ((kextpid = (long)vfork()) == 0) {
  245. chdir(tmp);
  246. execl(kextload,kextload,"-q","-repository",tmp,"tap.kext",(const char *)0);
  247. _exit(-1);
  248. } else {
  249. int exitcode = -1;
  250. waitpid(kextpid,&exitcode,0);
  251. usleep(500);
  252. }
  253. }
  254. if (stat("/dev/zt0",&tmp))
  255. throw std::runtime_error("/dev/zt# tap devices do not exist and unable to load kernel extension");
  256. // Open the first available device (ones in use will fail with resource busy)
  257. for(int i=0;i<256;++i) {
  258. sprintf(devpath,"/dev/zt%d",i);
  259. if (stat(devpath,&tmp))
  260. throw std::runtime_error("no more TAP devices available");
  261. _fd = ::open(devpath,O_RDWR);
  262. if (_fd > 0) {
  263. sprintf(_dev,"zt%d",i);
  264. break;
  265. }
  266. }
  267. if (_fd <= 0)
  268. throw std::runtime_error("unable to open TAP device or no more devices available");
  269. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  270. ::close(_fd);
  271. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  272. }
  273. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  274. if (!ifconfig) {
  275. ::close(_fd);
  276. throw std::runtime_error("unable to find 'ifconfig' command on system");
  277. }
  278. // Configure MAC address and MTU, bring interface up
  279. 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]);
  280. sprintf(mtustr,"%u",mtu);
  281. long cpid;
  282. if ((cpid = (long)vfork()) == 0) {
  283. execl(ifconfig,ifconfig,_dev,"lladdr",ethaddr,"mtu",mtustr,"up",(const char *)0);
  284. _exit(-1);
  285. } else {
  286. int exitcode = -1;
  287. waitpid(cpid,&exitcode,0);
  288. if (exitcode) {
  289. ::close(_fd);
  290. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  291. }
  292. }
  293. whack(); // turns on IPv6 on OSX
  294. ::pipe(_shutdownSignalPipe);
  295. _thread = Thread::start(this);
  296. }
  297. #endif // __APPLE__
  298. EthernetTap::~EthernetTap()
  299. {
  300. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  301. Thread::join(_thread);
  302. ::close(_fd);
  303. }
  304. #ifdef __APPLE__
  305. void EthernetTap::whack()
  306. {
  307. const char *ipconfig = UNIX_COMMANDS[ZT_MAC_IPCONFIG_COMMAND];
  308. if (ipconfig) {
  309. long cpid = (long)vfork();
  310. if (cpid == 0) {
  311. execl(ipconfig,ipconfig,"set",_dev,"AUTOMATIC-V6",(const char *)0);
  312. _exit(-1);
  313. } else {
  314. int exitcode = -1;
  315. waitpid(cpid,&exitcode,0);
  316. }
  317. }
  318. }
  319. #else
  320. void EthernetTap::whack() {}
  321. #endif // __APPLE__ / !__APPLE__
  322. #ifdef __LINUX__
  323. static bool ___removeIp(const char *_dev,const InetAddress &ip)
  324. {
  325. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  326. if (!ipcmd)
  327. return false;
  328. long cpid = (long)vfork();
  329. if (cpid == 0) {
  330. execl(ipcmd,ipcmd,"addr","del",ip.toString().c_str(),"dev",_dev,(const char *)0);
  331. _exit(-1);
  332. } else {
  333. int exitcode = -1;
  334. waitpid(cpid,&exitcode,0);
  335. return (exitcode == 0);
  336. }
  337. }
  338. bool EthernetTap::addIP(const InetAddress &ip)
  339. {
  340. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  341. if (!ipcmd) {
  342. LOG("ERROR: could not configure IP address for %s: unable to find 'ip' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev);
  343. return false;
  344. }
  345. Mutex::Lock _l(_ips_m);
  346. if (!ip)
  347. return false;
  348. if (_ips.count(ip) > 0)
  349. return true;
  350. // Remove and reconfigure if address is the same but netmask is different
  351. for(std::set<InetAddress>::iterator i(_ips.begin());i!=_ips.end();++i) {
  352. if (i->ipsEqual(ip)) {
  353. if (___removeIp(_dev,*i)) {
  354. _ips.erase(i);
  355. break;
  356. } else {
  357. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  358. }
  359. }
  360. }
  361. long cpid;
  362. if ((cpid = (long)vfork()) == 0) {
  363. execl(ipcmd,ipcmd,"addr","add",ip.toString().c_str(),"dev",_dev,(const char *)0);
  364. _exit(-1);
  365. } else {
  366. int exitcode = -1;
  367. waitpid(cpid,&exitcode,0);
  368. if (exitcode == 0) {
  369. _ips.insert(ip);
  370. return true;
  371. } else return false;
  372. }
  373. return false;
  374. }
  375. #endif // __LINUX__
  376. #ifdef __APPLE__
  377. static bool ___removeIp(const char *_dev,const InetAddress &ip)
  378. {
  379. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  380. if (!ifconfig)
  381. return false;
  382. long cpid;
  383. if ((cpid = (long)vfork()) == 0) {
  384. execl(ifconfig,ifconfig,_dev,"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  385. _exit(-1);
  386. } else {
  387. int exitcode = -1;
  388. waitpid(cpid,&exitcode,0);
  389. return (exitcode == 0);
  390. }
  391. return false; // never reached, make compiler shut up about return value
  392. }
  393. bool EthernetTap::addIP(const InetAddress &ip)
  394. {
  395. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  396. if (!ifconfig) {
  397. LOG("ERROR: could not configure IP address for %s: unable to find 'ifconfig' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev);
  398. return false;
  399. }
  400. Mutex::Lock _l(_ips_m);
  401. if (!ip)
  402. return false;
  403. if (_ips.count(ip) > 0)
  404. return true; // IP/netmask already assigned
  405. // Remove and reconfigure if address is the same but netmask is different
  406. for(std::set<InetAddress>::iterator i(_ips.begin());i!=_ips.end();++i) {
  407. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  408. if (___removeIp(_dev,*i)) {
  409. _ips.erase(i);
  410. break;
  411. } else {
  412. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  413. }
  414. }
  415. }
  416. long cpid;
  417. if ((cpid = (long)vfork()) == 0) {
  418. execl(ifconfig,ifconfig,_dev,ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  419. _exit(-1);
  420. } else {
  421. int exitcode = -1;
  422. waitpid(cpid,&exitcode,0);
  423. if (exitcode == 0) {
  424. _ips.insert(ip);
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. #endif // __APPLE__
  431. bool EthernetTap::removeIP(const InetAddress &ip)
  432. {
  433. Mutex::Lock _l(_ips_m);
  434. if (_ips.count(ip) > 0) {
  435. if (___removeIp(_dev,ip)) {
  436. _ips.erase(ip);
  437. return true;
  438. }
  439. }
  440. return false;
  441. }
  442. void EthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  443. {
  444. char putBuf[4096 + 14];
  445. if ((_fd > 0)&&(len <= _mtu)) {
  446. for(int i=0;i<6;++i)
  447. putBuf[i] = to.data[i];
  448. for(int i=0;i<6;++i)
  449. putBuf[i+6] = from.data[i];
  450. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  451. memcpy(putBuf + 14,data,len);
  452. len += 14;
  453. int n = ::write(_fd,putBuf,len);
  454. if (n <= 0) {
  455. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  456. } else if (n != (int)len) {
  457. // Saw this gremlin once, so log it if we see it again... OSX tap
  458. // or something seems to have goofy issues with certain MTUs.
  459. LOG("ERROR: write underrun: %s tap write() wrote %d of %u bytes of frame",_dev,n,len);
  460. }
  461. }
  462. }
  463. std::string EthernetTap::deviceName() const
  464. {
  465. return std::string(_dev);
  466. }
  467. #ifdef __LINUX__
  468. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  469. {
  470. char *ptr,*ptr2;
  471. unsigned char mac[6];
  472. std::set<MulticastGroup> newGroups;
  473. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  474. if (fd > 0) {
  475. char buf[131072];
  476. int n = (int)::read(fd,buf,sizeof(buf));
  477. if ((n > 0)&&(n < (int)sizeof(buf))) {
  478. buf[n] = (char)0;
  479. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  480. int fno = 0;
  481. char *devname = (char *)0;
  482. char *mcastmac = (char *)0;
  483. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  484. if (fno == 1)
  485. devname = f;
  486. else if (fno == 4)
  487. mcastmac = f;
  488. ++fno;
  489. }
  490. if ((devname)&&(!strcmp(devname,_dev))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  491. newGroups.insert(MulticastGroup(MAC(mac),0));
  492. }
  493. }
  494. ::close(fd);
  495. }
  496. {
  497. Mutex::Lock _l(_ips_m);
  498. for(std::set<InetAddress>::const_iterator i(_ips.begin());i!=_ips.end();++i)
  499. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  500. }
  501. bool changed = false;
  502. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  503. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  504. if (!groups.count(*mg)) {
  505. groups.insert(*mg);
  506. changed = true;
  507. }
  508. }
  509. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  510. if (!newGroups.count(*mg)) {
  511. groups.erase(mg++);
  512. changed = true;
  513. } else ++mg;
  514. }
  515. return changed;
  516. }
  517. #endif // __LINUX__
  518. #ifdef __APPLE__
  519. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  520. {
  521. std::set<MulticastGroup> newGroups;
  522. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  523. if (!getifmaddrs(&ifmap)) {
  524. struct ifmaddrs *p = ifmap;
  525. while (p) {
  526. if (p->ifma_addr->sa_family == AF_LINK) {
  527. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  528. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  529. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= sizeof(_dev))&&(!memcmp(_dev,in->sdl_data,in->sdl_nlen)))
  530. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen),0));
  531. }
  532. p = p->ifma_next;
  533. }
  534. freeifmaddrs(ifmap);
  535. }
  536. {
  537. Mutex::Lock _l(_ips_m);
  538. for(std::set<InetAddress>::const_iterator i(_ips.begin());i!=_ips.end();++i)
  539. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  540. }
  541. bool changed = false;
  542. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  543. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  544. if (!groups.count(*mg)) {
  545. groups.insert(*mg);
  546. changed = true;
  547. }
  548. }
  549. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  550. if (!newGroups.count(*mg)) {
  551. groups.erase(mg++);
  552. changed = true;
  553. } else ++mg;
  554. }
  555. return changed;
  556. }
  557. #endif // __APPLE__
  558. void EthernetTap::threadMain()
  559. throw()
  560. {
  561. fd_set readfds,nullfds;
  562. MAC to,from;
  563. char getBuf[4096 + 14];
  564. Buffer<4096> data;
  565. // Wait for a moment after startup -- wait for Network to finish
  566. // constructing itself.
  567. Thread::sleep(500);
  568. FD_ZERO(&readfds);
  569. FD_ZERO(&nullfds);
  570. int nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  571. for(;;) {
  572. FD_SET(_shutdownSignalPipe[0],&readfds);
  573. FD_SET(_fd,&readfds);
  574. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  575. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  576. break;
  577. if (FD_ISSET(_fd,&readfds)) {
  578. int n = (int)::read(_fd,getBuf,_mtu + 14);
  579. if (n > 14) {
  580. for(int i=0;i<6;++i)
  581. to.data[i] = (unsigned char)getBuf[i];
  582. for(int i=0;i<6;++i)
  583. from.data[i] = (unsigned char)getBuf[i + 6];
  584. data.copyFrom(getBuf + 14,(unsigned int)n - 14);
  585. _handler(_arg,from,to,ntohs(((const uint16_t *)getBuf)[6]),data);
  586. } else if (n < 0) {
  587. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  588. TRACE("unexpected error reading from tap: %s",strerror(errno));
  589. break;
  590. }
  591. }
  592. }
  593. }
  594. }
  595. } // namespace ZeroTier
  596. #endif // __UNIX_LIKE__ //////////////////////////////////////////////////////
  597. //////////////////////////////////////////////////////////////////////////////
  598. #ifdef __WINDOWS__ ///////////////////////////////////////////////////////////
  599. #include <stdio.h>
  600. #include <stdlib.h>
  601. #include <stdint.h>
  602. #include <string.h>
  603. #include <WinSock2.h>
  604. #include <Windows.h>
  605. #include <iphlpapi.h>
  606. #include <ws2ipdef.h>
  607. #include <WS2tcpip.h>
  608. #include <tchar.h>
  609. #include <winreg.h>
  610. #include <wchar.h>
  611. #include <nldef.h>
  612. #include <netioapi.h>
  613. #include "..\vsprojects\TapDriver\tap-windows.h"
  614. namespace ZeroTier {
  615. // Helper function to get an adapter's LUID and index from its GUID. The LUID is
  616. // constant but the index can change, so go ahead and just look them both up by
  617. // the GUID which is constant. (The GUID is the instance ID in the registry.)
  618. static inline std::pair<NET_LUID,NET_IFINDEX> _findAdapterByGuid(const GUID &guid)
  619. throw(std::runtime_error)
  620. {
  621. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  622. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  623. throw std::runtime_error("GetIfTable2Ex() failed");
  624. for(ULONG i=0;i<ift->NumEntries;++i) {
  625. if (ift->Table[i].InterfaceGuid == guid) {
  626. std::pair<NET_LUID,NET_IFINDEX> tmp(ift->Table[i].InterfaceLuid,ift->Table[i].InterfaceIndex);
  627. FreeMibTable(ift);
  628. return tmp;
  629. }
  630. }
  631. FreeMibTable(&ift);
  632. throw std::runtime_error("interface not found");
  633. }
  634. static Mutex _systemTapInitLock;
  635. EthernetTap::EthernetTap(
  636. const RuntimeEnvironment *renv,
  637. const char *tag,
  638. const MAC &mac,
  639. unsigned int mtu,
  640. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  641. void *arg)
  642. throw(std::runtime_error) :
  643. _mac(mac),
  644. _mtu(mtu),
  645. _r(renv),
  646. _handler(handler),
  647. _arg(arg),
  648. _dhcp(false),
  649. _dhcp6(false),
  650. _tap(INVALID_HANDLE_VALUE),
  651. _injectSemaphore(INVALID_HANDLE_VALUE),
  652. _run(true)
  653. {
  654. char subkeyName[4096];
  655. char subkeyClass[4096];
  656. char data[4096];
  657. if (mtu > ZT_IF_MTU)
  658. throw std::runtime_error("MTU too large for Windows tap");
  659. #ifdef _WIN64
  660. const char *devcon = "\\devcon64.exe";
  661. #else
  662. BOOL f64 = FALSE;
  663. const char *devcon = ((IsWow64Process(GetCurrentProcess(),&f64) == TRUE) ? "\\devcon64.exe" : "\\devcon32.exe");
  664. #endif
  665. Mutex::Lock _l(_systemTapInitLock); // only init one tap at a time, process-wide
  666. HKEY nwAdapters;
  667. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  668. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  669. std::set<std::string> existingDeviceInstances;
  670. std::string mySubkeyName;
  671. // Enumerate tap instances and look for one tagged with this tag
  672. for(DWORD subkeyIndex=0;subkeyIndex!=-1;) {
  673. DWORD type;
  674. DWORD dataLen;
  675. DWORD subkeyNameLen = sizeof(subkeyName);
  676. DWORD subkeyClassLen = sizeof(subkeyClass);
  677. FILETIME lastWriteTime;
  678. switch (RegEnumKeyExA(nwAdapters,subkeyIndex++,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime)) {
  679. case ERROR_NO_MORE_ITEMS: subkeyIndex = -1; break;
  680. case ERROR_SUCCESS:
  681. type = 0;
  682. dataLen = sizeof(data);
  683. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  684. data[dataLen] = '\0';
  685. if (!strnicmp(data,"zttap",5)) {
  686. std::string instanceId;
  687. type = 0;
  688. dataLen = sizeof(data);
  689. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  690. instanceId.assign(data,dataLen);
  691. existingDeviceInstances.insert(instanceId);
  692. }
  693. std::string instanceIdPath;
  694. type = 0;
  695. dataLen = sizeof(data);
  696. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  697. instanceIdPath.assign(data,dataLen);
  698. if ((_myDeviceInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  699. type = 0;
  700. dataLen = sizeof(data);
  701. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  702. data[dataLen] = '\0';
  703. if (!strcmp(data,tag)) {
  704. _myDeviceInstanceId = instanceId;
  705. _myDeviceInstanceIdPath = instanceIdPath;
  706. mySubkeyName = subkeyName;
  707. subkeyIndex = -1; // break outer loop
  708. }
  709. }
  710. }
  711. }
  712. }
  713. break;
  714. }
  715. }
  716. // If there is no device, try to create one
  717. if (_myDeviceInstanceId.length() == 0) {
  718. // Execute devcon to install an instance of the Microsoft Loopback Adapter
  719. STARTUPINFOA startupInfo;
  720. startupInfo.cb = sizeof(startupInfo);
  721. PROCESS_INFORMATION processInfo;
  722. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  723. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  724. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + devcon + "\" install \"" + _r->homePath + "\\ztTap100.inf\" ztTap100").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  725. RegCloseKey(nwAdapters);
  726. throw std::runtime_error(std::string("unable to find or execute devcon at ")+devcon);
  727. }
  728. WaitForSingleObject(processInfo.hProcess,INFINITE);
  729. CloseHandle(processInfo.hProcess);
  730. CloseHandle(processInfo.hThread);
  731. // Scan for the new instance by simply looking for taps that weren't
  732. // there originally.
  733. for(DWORD subkeyIndex=0;subkeyIndex!=-1;) {
  734. DWORD type;
  735. DWORD dataLen;
  736. DWORD subkeyNameLen = sizeof(subkeyName);
  737. DWORD subkeyClassLen = sizeof(subkeyClass);
  738. FILETIME lastWriteTime;
  739. switch (RegEnumKeyExA(nwAdapters,subkeyIndex++,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime)) {
  740. case ERROR_NO_MORE_ITEMS: subkeyIndex = -1; break;
  741. case ERROR_SUCCESS:
  742. type = 0;
  743. dataLen = sizeof(data);
  744. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  745. data[dataLen] = '\0';
  746. if (!strnicmp(data,"zttap",5)) {
  747. type = 0;
  748. dataLen = sizeof(data);
  749. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  750. if (existingDeviceInstances.count(std::string(data,dataLen)) == 0) {
  751. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  752. _myDeviceInstanceId.assign(data,dataLen);
  753. type = 0;
  754. dataLen = sizeof(data);
  755. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  756. _myDeviceInstanceIdPath.assign(data,dataLen);
  757. mySubkeyName = subkeyName;
  758. subkeyIndex = -1; // break outer loop
  759. }
  760. }
  761. }
  762. }
  763. break;
  764. }
  765. }
  766. }
  767. // If we have a device, configure it
  768. if (_myDeviceInstanceId.length() > 0) {
  769. char tmps[4096];
  770. unsigned int tmpsl = sprintf_s(tmps,"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X",(unsigned int)mac.data[0],(unsigned int)mac.data[1],(unsigned int)mac.data[2],(unsigned int)mac.data[3],(unsigned int)mac.data[4],(unsigned int)mac.data[5]) + 1;
  771. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  772. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  773. DWORD tmp = mtu;
  774. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MTU",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  775. tmp = 0;
  776. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  777. }
  778. // Done with registry
  779. RegCloseKey(nwAdapters);
  780. // If we didn't get a device, we can't start
  781. if (_myDeviceInstanceId.length() == 0)
  782. throw std::runtime_error("unable to create new tap adapter");
  783. // Convert device GUID junk... blech
  784. {
  785. char nobraces[128];
  786. const char *nbtmp1 = _myDeviceInstanceId.c_str();
  787. char *nbtmp2 = nobraces;
  788. while (*nbtmp1) {
  789. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  790. *nbtmp2++ = *nbtmp1;
  791. ++nbtmp1;
  792. }
  793. *nbtmp2 = (char)0;
  794. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  795. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  796. }
  797. setDhcpEnabled(false);
  798. setDhcp6Enabled(false);
  799. // Disable and enable interface to ensure registry settings take effect
  800. {
  801. STARTUPINFOA startupInfo;
  802. startupInfo.cb = sizeof(startupInfo);
  803. PROCESS_INFORMATION processInfo;
  804. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  805. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  806. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + devcon + "\" disable @" + _myDeviceInstanceIdPath).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  807. RegCloseKey(nwAdapters);
  808. throw std::runtime_error(std::string("unable to find or execute devcon at ")+devcon);
  809. }
  810. WaitForSingleObject(processInfo.hProcess,INFINITE);
  811. CloseHandle(processInfo.hProcess);
  812. CloseHandle(processInfo.hThread);
  813. }
  814. {
  815. STARTUPINFOA startupInfo;
  816. startupInfo.cb = sizeof(startupInfo);
  817. PROCESS_INFORMATION processInfo;
  818. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  819. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  820. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + devcon + "\" enable @" + _myDeviceInstanceIdPath).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  821. RegCloseKey(nwAdapters);
  822. throw std::runtime_error(std::string("unable to find or execute devcon at ")+devcon);
  823. }
  824. WaitForSingleObject(processInfo.hProcess,INFINITE);
  825. CloseHandle(processInfo.hProcess);
  826. CloseHandle(processInfo.hThread);
  827. }
  828. // Open the tap, which is in this weird Windows analog of /dev
  829. char tapPath[4096];
  830. sprintf_s(tapPath,"\\\\.\\Global\\%s.tap",_myDeviceInstanceId.c_str());
  831. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  832. if (_tap == INVALID_HANDLE_VALUE)
  833. throw std::runtime_error("unable to open tap in \\\\.\\Global\\ namespace");
  834. // Set media status to enabled
  835. uint32_t tmpi = 1;
  836. DWORD bytesReturned = 0;
  837. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  838. // Initialized overlapped I/O structures and related events
  839. memset(&_tapOvlRead,0,sizeof(_tapOvlRead));
  840. _tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  841. memset(&_tapOvlWrite,0,sizeof(_tapOvlWrite));
  842. _tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  843. // Start background thread that actually performs I/O
  844. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  845. _thread = Thread::start(this);
  846. }
  847. EthernetTap::~EthernetTap()
  848. {
  849. _run = false;
  850. ReleaseSemaphore(_injectSemaphore,1,NULL);
  851. Thread::join(_thread);
  852. CloseHandle(_tap);
  853. CloseHandle(_tapOvlRead.hEvent);
  854. CloseHandle(_tapOvlWrite.hEvent);
  855. CloseHandle(_injectSemaphore);
  856. // Disable network device on shutdown
  857. #ifdef _WIN64
  858. const char *devcon = "\\devcon64.exe";
  859. #else
  860. BOOL f64 = FALSE;
  861. const char *devcon = ((IsWow64Process(GetCurrentProcess(),&f64) == TRUE) ? "\\devcon64.exe" : "\\devcon32.exe");
  862. #endif
  863. {
  864. STARTUPINFOA startupInfo;
  865. startupInfo.cb = sizeof(startupInfo);
  866. PROCESS_INFORMATION processInfo;
  867. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  868. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  869. if (CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + devcon + "\" disable @" + _myDeviceInstanceIdPath).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  870. WaitForSingleObject(processInfo.hProcess,INFINITE);
  871. CloseHandle(processInfo.hProcess);
  872. CloseHandle(processInfo.hThread);
  873. }
  874. }
  875. }
  876. void EthernetTap::whack()
  877. {
  878. }
  879. bool EthernetTap::setDhcpEnabled(bool dhcp)
  880. {
  881. HKEY tcpIpInterfaces;
  882. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  883. _dhcp = dhcp;
  884. DWORD enable = (dhcp ? 1 : 0);
  885. RegSetKeyValueA(tcpIpInterfaces,_myDeviceInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  886. RegCloseKey(tcpIpInterfaces);
  887. } else _dhcp = false;
  888. return _dhcp;
  889. }
  890. bool EthernetTap::setDhcp6Enabled(bool dhcp)
  891. {
  892. // TODO
  893. return _dhcp6;
  894. }
  895. void EthernetTap::setDisplayName(const char *dn)
  896. {
  897. HKEY ifp;
  898. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,(std::string("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\") + _myDeviceInstanceId).c_str(),0,KEY_READ|KEY_WRITE,&ifp) == ERROR_SUCCESS) {
  899. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  900. RegCloseKey(ifp);
  901. }
  902. }
  903. bool EthernetTap::addIP(const InetAddress &ip)
  904. {
  905. Mutex::Lock _l(_ips_m);
  906. if (_ips.count(ip))
  907. return true;
  908. if (!ip.port())
  909. return false;
  910. try {
  911. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  912. MIB_UNICASTIPADDRESS_ROW ipr;
  913. InitializeUnicastIpAddressEntry(&ipr);
  914. if (ip.isV4()) {
  915. ipr.Address.Ipv4.sin_family = AF_INET;
  916. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)ip.rawIpData());
  917. ipr.OnLinkPrefixLength = ip.port();
  918. } else if (ip.isV6()) {
  919. } else return false;
  920. ipr.PrefixOrigin = IpPrefixOriginManual;
  921. ipr.SuffixOrigin = IpSuffixOriginManual;
  922. ipr.ValidLifetime = 0xffffffff;
  923. ipr.PreferredLifetime = 0xffffffff;
  924. ipr.InterfaceLuid = ifidx.first;
  925. ipr.InterfaceIndex = ifidx.second;
  926. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  927. _ips.insert(ip);
  928. return true;
  929. }
  930. } catch ( ... ) {}
  931. return false;
  932. }
  933. bool EthernetTap::removeIP(const InetAddress &ip)
  934. {
  935. try {
  936. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  937. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  938. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  939. for(DWORD i=0;i<ipt->NumEntries;++i) {
  940. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  941. InetAddress addr;
  942. switch(ipt->Table[i].Address.si_family) {
  943. case AF_INET:
  944. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  945. break;
  946. case AF_INET6:
  947. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  948. break;
  949. }
  950. if (addr == ip) {
  951. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  952. FreeMibTable(ipt);
  953. Mutex::Lock _l(_ips_m);
  954. _ips.erase(ip);
  955. return true;
  956. }
  957. }
  958. }
  959. FreeMibTable(&ipt);
  960. }
  961. } catch ( ... ) {}
  962. return false;
  963. }
  964. std::set<InetAddress> EthernetTap::allIps() const
  965. {
  966. static const InetAddress ifLoopback("fe80::1",64);
  967. std::set<InetAddress> addrs;
  968. try {
  969. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  970. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  971. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  972. for(DWORD i=0;i<ipt->NumEntries;++i) {
  973. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  974. switch(ipt->Table[i].Address.si_family) {
  975. case AF_INET:
  976. addrs.insert(InetAddress(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength));
  977. break;
  978. case AF_INET6: {
  979. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  980. if (ip != ifLoopback) // don't include fe80::1
  981. addrs.insert(ip);
  982. } break;
  983. }
  984. }
  985. }
  986. FreeMibTable(ipt);
  987. }
  988. } catch ( ... ) {}
  989. return addrs;
  990. }
  991. void EthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  992. {
  993. if (len > (ZT_IF_MTU))
  994. return;
  995. {
  996. Mutex::Lock _l(_injectPending_m);
  997. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  998. char *d = _injectPending.back().first.data;
  999. memcpy(d,to.data,6);
  1000. memcpy(d + 6,from.data,6);
  1001. *((uint16_t *)(d + 12)) = Utils::hton(etherType);
  1002. memcpy(d + 14,data,len);
  1003. }
  1004. ReleaseSemaphore(_injectSemaphore,1,NULL);
  1005. }
  1006. std::string EthernetTap::deviceName() const
  1007. {
  1008. return _myDeviceInstanceId;
  1009. }
  1010. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  1011. {
  1012. std::set<MulticastGroup> newGroups;
  1013. std::set<InetAddress> ipaddrs(allIps());
  1014. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  1015. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  1016. bool changed = false;
  1017. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  1018. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  1019. if (!groups.count(*mg)) {
  1020. groups.insert(*mg);
  1021. changed = true;
  1022. }
  1023. }
  1024. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  1025. if (!newGroups.count(*mg)) {
  1026. groups.erase(mg++);
  1027. changed = true;
  1028. } else ++mg;
  1029. }
  1030. return changed;
  1031. }
  1032. void EthernetTap::threadMain()
  1033. throw()
  1034. {
  1035. HANDLE wait4[3];
  1036. wait4[0] = _injectSemaphore;
  1037. wait4[1] = _tapOvlRead.hEvent;
  1038. wait4[2] = _tapOvlWrite.hEvent;
  1039. ReadFile(_tap,_tapReadBuf,sizeof(_tapReadBuf),NULL,&_tapOvlRead);
  1040. bool writeInProgress = false;
  1041. for(;;) {
  1042. if (!_run) break;
  1043. WaitForMultipleObjectsEx(3,wait4,FALSE,INFINITE,TRUE);
  1044. if (!_run) break;
  1045. if (HasOverlappedIoCompleted(&_tapOvlRead)) {
  1046. DWORD bytesRead = 0;
  1047. if (GetOverlappedResult(_tap,&_tapOvlRead,&bytesRead,FALSE)) {
  1048. if (bytesRead > 14) {
  1049. MAC to(_tapReadBuf);
  1050. MAC from(_tapReadBuf + 6);
  1051. unsigned int etherType = Utils::ntoh(*((const uint16_t *)(_tapReadBuf + 12)));
  1052. Buffer<4096> tmp(_tapReadBuf + 14,bytesRead - 14);
  1053. //printf("GOT FRAME: %u bytes: %s\r\n",(unsigned int)bytesRead,Utils::hex(_tapReadBuf,bytesRead).c_str());
  1054. _handler(_arg,from,to,etherType,tmp);
  1055. }
  1056. }
  1057. ReadFile(_tap,_tapReadBuf,sizeof(_tapReadBuf),NULL,&_tapOvlRead);
  1058. }
  1059. if (writeInProgress) {
  1060. if (HasOverlappedIoCompleted(&_tapOvlWrite)) {
  1061. writeInProgress = false;
  1062. _injectPending_m.lock();
  1063. _injectPending.pop();
  1064. } else continue; // still writing, so skip code below and wait
  1065. } else _injectPending_m.lock();
  1066. if (!_injectPending.empty()) {
  1067. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&_tapOvlWrite);
  1068. writeInProgress = true;
  1069. }
  1070. _injectPending_m.unlock();
  1071. }
  1072. CancelIo(_tap);
  1073. }
  1074. } // namespace ZeroTier
  1075. #endif // __WINDOWS__ ////////////////////////////////////////////////////////