EthernetTap.cpp 48 KB

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