EthernetTap.cpp 36 KB

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