EthernetTap.cpp 46 KB

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