EthernetTap.cpp 54 KB

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