EthernetTap.cpp 41 KB

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