EthernetTap.cpp 46 KB

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