EthernetTap.cpp 37 KB

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