EthernetTap.cpp 36 KB

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