EthernetTap.cpp 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. // ff:ff:ff:ff:ff:ff with no ADI
  38. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  39. //
  40. // TAP implementation for *nix OSes, with some specialization for different flavors
  41. //
  42. #ifdef __UNIX_LIKE__ /////////////////////////////////////////////////////////
  43. #include <stdint.h>
  44. #include <stdio.h>
  45. #include <stdlib.h>
  46. #include <string.h>
  47. #include <unistd.h>
  48. #include <signal.h>
  49. #include <fcntl.h>
  50. #include <errno.h>
  51. #include <sys/types.h>
  52. #include <sys/stat.h>
  53. #include <sys/ioctl.h>
  54. #include <sys/wait.h>
  55. #include <sys/select.h>
  56. #include <netinet/in.h>
  57. #include <net/if_arp.h>
  58. #include <arpa/inet.h>
  59. // Command identifiers used with command finder static (on various *nixes)
  60. #define ZT_UNIX_IP_COMMAND 1
  61. #define ZT_UNIX_IFCONFIG_COMMAND 2
  62. #define ZT_MAC_KEXTLOAD_COMMAND 3
  63. #define ZT_MAC_IPCONFIG_COMMAND 4
  64. // Finds external commands on startup
  65. class _CommandFinder
  66. {
  67. public:
  68. _CommandFinder()
  69. {
  70. _findCmd(ZT_UNIX_IFCONFIG_COMMAND,"ifconfig");
  71. #ifdef __LINUX__
  72. _findCmd(ZT_UNIX_IP_COMMAND,"ip");
  73. #endif
  74. #ifdef __APPLE__
  75. _findCmd(ZT_MAC_KEXTLOAD_COMMAND,"kextload");
  76. _findCmd(ZT_MAC_IPCONFIG_COMMAND,"ipconfig");
  77. #endif
  78. }
  79. // returns NULL if command was not found
  80. inline const char *operator[](int id) const
  81. throw()
  82. {
  83. std::map<int,std::string>::const_iterator c(_paths.find(id));
  84. if (c == _paths.end())
  85. return (const char *)0;
  86. return c->second.c_str();
  87. }
  88. private:
  89. inline void _findCmd(int id,const char *name)
  90. {
  91. char tmp[4096];
  92. sprintf(tmp,"/sbin/%s",name);
  93. if (ZeroTier::Utils::fileExists(tmp)) {
  94. _paths[id] = tmp;
  95. return;
  96. }
  97. sprintf(tmp,"/usr/sbin/%s",name);
  98. if (ZeroTier::Utils::fileExists(tmp)) {
  99. _paths[id] = tmp;
  100. return;
  101. }
  102. sprintf(tmp,"/bin/%s",name);
  103. if (ZeroTier::Utils::fileExists(tmp)) {
  104. _paths[id] = tmp;
  105. return;
  106. }
  107. sprintf(tmp,"/usr/bin/%s",name);
  108. if (ZeroTier::Utils::fileExists(tmp)) {
  109. _paths[id] = tmp;
  110. return;
  111. }
  112. }
  113. std::map<int,std::string> _paths;
  114. };
  115. static const _CommandFinder UNIX_COMMANDS;
  116. #ifdef __LINUX__
  117. #include <linux/if.h>
  118. #include <linux/if_tun.h>
  119. #include <linux/if_addr.h>
  120. #include <linux/if_ether.h>
  121. #endif // __LINUX__
  122. #ifdef __APPLE__
  123. #include <sys/uio.h>
  124. #include <sys/param.h>
  125. #include <sys/sysctl.h>
  126. #include <net/route.h>
  127. #include <net/if_dl.h>
  128. #include <ifaddrs.h>
  129. #endif // __APPLE__
  130. namespace ZeroTier {
  131. // Only permit one tap to be opened concurrently across the entire process
  132. static Mutex __tapCreateLock;
  133. #ifdef __LINUX__
  134. EthernetTap::EthernetTap(
  135. const RuntimeEnvironment *renv,
  136. const char *tag,
  137. const MAC &mac,
  138. unsigned int mtu,
  139. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  140. void *arg)
  141. throw(std::runtime_error) :
  142. _mac(mac),
  143. _mtu(mtu),
  144. _r(renv),
  145. _handler(handler),
  146. _arg(arg),
  147. _fd(0)
  148. {
  149. char procpath[128];
  150. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  151. if (mtu > 4096)
  152. throw std::runtime_error("max tap MTU is 4096");
  153. _fd = ::open("/dev/net/tun",O_RDWR);
  154. if (_fd <= 0)
  155. throw std::runtime_error(std::string("could not open TUN/TAP device: ") + strerror(errno));
  156. struct ifreq ifr;
  157. memset(&ifr,0,sizeof(ifr));
  158. { // pick an unused device name
  159. int devno = 0;
  160. struct stat sbuf;
  161. do {
  162. sprintf(ifr.ifr_name,"zt%d",devno++);
  163. sprintf(procpath,"/proc/sys/net/ipv4/conf/%s",ifr.ifr_name);
  164. } while (stat(procpath,&sbuf) == 0);
  165. }
  166. ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
  167. if (ioctl(_fd,TUNSETIFF,(void *)&ifr) < 0) {
  168. ::close(_fd);
  169. throw std::runtime_error("unable to configure TUN/TAP device for TAP operation");
  170. }
  171. strcpy(_dev,ifr.ifr_name);
  172. ioctl(_fd,TUNSETPERSIST,0); // valgrind may generate a false alarm here
  173. // Open an arbitrary socket to talk to netlink
  174. int sock = socket(AF_INET,SOCK_DGRAM,0);
  175. if (sock <= 0) {
  176. ::close(_fd);
  177. throw std::runtime_error("unable to open netlink socket");
  178. }
  179. // Set MAC address
  180. ifr.ifr_ifru.ifru_hwaddr.sa_family = ARPHRD_ETHER;
  181. memcpy(ifr.ifr_ifru.ifru_hwaddr.sa_data,mac.data,6);
  182. if (ioctl(sock,SIOCSIFHWADDR,(void *)&ifr) < 0) {
  183. ::close(_fd);
  184. ::close(sock);
  185. throw std::runtime_error("unable to configure TAP hardware (MAC) address");
  186. return;
  187. }
  188. // Set MTU
  189. ifr.ifr_ifru.ifru_mtu = (int)mtu;
  190. if (ioctl(sock,SIOCSIFMTU,(void *)&ifr) < 0) {
  191. ::close(_fd);
  192. ::close(sock);
  193. throw std::runtime_error("unable to configure TAP MTU");
  194. }
  195. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  196. ::close(_fd);
  197. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  198. }
  199. /* Bring interface up */
  200. if (ioctl(sock,SIOCGIFFLAGS,(void *)&ifr) < 0) {
  201. ::close(_fd);
  202. ::close(sock);
  203. throw std::runtime_error("unable to get TAP interface flags");
  204. }
  205. ifr.ifr_flags |= IFF_UP;
  206. if (ioctl(sock,SIOCSIFFLAGS,(void *)&ifr) < 0) {
  207. ::close(_fd);
  208. ::close(sock);
  209. throw std::runtime_error("unable to set TAP interface flags");
  210. }
  211. ::close(sock);
  212. ::pipe(_shutdownSignalPipe);
  213. TRACE("tap %s created",_dev);
  214. _thread = Thread::start(this);
  215. }
  216. #endif // __LINUX__
  217. #ifdef __APPLE__
  218. EthernetTap::EthernetTap(
  219. const RuntimeEnvironment *renv,
  220. const char *tag,
  221. const MAC &mac,
  222. unsigned int mtu,
  223. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  224. void *arg)
  225. throw(std::runtime_error) :
  226. _mac(mac),
  227. _mtu(mtu),
  228. _r(renv),
  229. _handler(handler),
  230. _arg(arg),
  231. _fd(0)
  232. {
  233. char devpath[64],ethaddr[64],mtustr[16];
  234. struct stat tmp;
  235. Mutex::Lock _l(__tapCreateLock); // create only one tap at a time, globally
  236. if (mtu > 4096)
  237. throw std::runtime_error("max tap MTU is 4096");
  238. // Check for existence of ZT tap devices, try to load module if not there
  239. const char *kextload = UNIX_COMMANDS[ZT_MAC_KEXTLOAD_COMMAND];
  240. if ((stat("/dev/zt0",&tmp))&&(kextload)) {
  241. long kextpid;
  242. char tmp[4096];
  243. strcpy(tmp,_r->homePath.c_str());
  244. if ((kextpid = (long)vfork()) == 0) {
  245. chdir(tmp);
  246. execl(kextload,kextload,"-q","-repository",tmp,"tap.kext",(const char *)0);
  247. _exit(-1);
  248. } else {
  249. int exitcode = -1;
  250. waitpid(kextpid,&exitcode,0);
  251. usleep(500);
  252. }
  253. }
  254. if (stat("/dev/zt0",&tmp))
  255. throw std::runtime_error("/dev/zt# tap devices do not exist and unable to load kernel extension");
  256. // Open the first available device (ones in use will fail with resource busy)
  257. for(int i=0;i<256;++i) {
  258. sprintf(devpath,"/dev/zt%d",i);
  259. if (stat(devpath,&tmp))
  260. throw std::runtime_error("no more TAP devices available");
  261. _fd = ::open(devpath,O_RDWR);
  262. if (_fd > 0) {
  263. sprintf(_dev,"zt%d",i);
  264. break;
  265. }
  266. }
  267. if (_fd <= 0)
  268. throw std::runtime_error("unable to open TAP device or no more devices available");
  269. if (fcntl(_fd,F_SETFL,fcntl(_fd,F_GETFL) & ~O_NONBLOCK) == -1) {
  270. ::close(_fd);
  271. throw std::runtime_error("unable to set flags on file descriptor for TAP device");
  272. }
  273. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  274. if (!ifconfig) {
  275. ::close(_fd);
  276. throw std::runtime_error("unable to find 'ifconfig' command on system");
  277. }
  278. // Configure MAC address and MTU, bring interface up
  279. sprintf(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]);
  280. sprintf(mtustr,"%u",mtu);
  281. long cpid;
  282. if ((cpid = (long)vfork()) == 0) {
  283. execl(ifconfig,ifconfig,_dev,"lladdr",ethaddr,"mtu",mtustr,"up",(const char *)0);
  284. _exit(-1);
  285. } else {
  286. int exitcode = -1;
  287. waitpid(cpid,&exitcode,0);
  288. if (exitcode) {
  289. ::close(_fd);
  290. throw std::runtime_error("ifconfig failure setting link-layer address and activating tap interface");
  291. }
  292. }
  293. whack(); // turns on IPv6 on OSX
  294. ::pipe(_shutdownSignalPipe);
  295. _thread = Thread::start(this);
  296. }
  297. #endif // __APPLE__
  298. EthernetTap::~EthernetTap()
  299. {
  300. ::write(_shutdownSignalPipe[1],"\0",1); // causes thread to exit
  301. Thread::join(_thread);
  302. ::close(_fd);
  303. }
  304. #ifdef __APPLE__
  305. void EthernetTap::whack()
  306. {
  307. const char *ipconfig = UNIX_COMMANDS[ZT_MAC_IPCONFIG_COMMAND];
  308. if (ipconfig) {
  309. long cpid = (long)vfork();
  310. if (cpid == 0) {
  311. execl(ipconfig,ipconfig,"set",_dev,"AUTOMATIC-V6",(const char *)0);
  312. _exit(-1);
  313. } else {
  314. int exitcode = -1;
  315. waitpid(cpid,&exitcode,0);
  316. }
  317. }
  318. }
  319. #else
  320. void EthernetTap::whack() {}
  321. #endif // __APPLE__ / !__APPLE__
  322. #ifdef __LINUX__
  323. static bool ___removeIp(const char *_dev,const InetAddress &ip)
  324. {
  325. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  326. if (!ipcmd)
  327. return false;
  328. long cpid = (long)vfork();
  329. if (cpid == 0) {
  330. execl(ipcmd,ipcmd,"addr","del",ip.toString().c_str(),"dev",_dev,(const char *)0);
  331. _exit(-1);
  332. } else {
  333. int exitcode = -1;
  334. waitpid(cpid,&exitcode,0);
  335. return (exitcode == 0);
  336. }
  337. }
  338. bool EthernetTap::addIP(const InetAddress &ip)
  339. {
  340. const char *ipcmd = UNIX_COMMANDS[ZT_UNIX_IP_COMMAND];
  341. if (!ipcmd) {
  342. LOG("ERROR: could not configure IP address for %s: unable to find 'ip' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev);
  343. return false;
  344. }
  345. Mutex::Lock _l(_ips_m);
  346. if (!ip)
  347. return false;
  348. if (_ips.count(ip) > 0)
  349. return true;
  350. // Remove and reconfigure if address is the same but netmask is different
  351. for(std::set<InetAddress>::iterator i(_ips.begin());i!=_ips.end();++i) {
  352. if (i->ipsEqual(ip)) {
  353. if (___removeIp(_dev,*i)) {
  354. _ips.erase(i);
  355. break;
  356. } else {
  357. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  358. }
  359. }
  360. }
  361. long cpid;
  362. if ((cpid = (long)vfork()) == 0) {
  363. execl(ipcmd,ipcmd,"addr","add",ip.toString().c_str(),"dev",_dev,(const char *)0);
  364. _exit(-1);
  365. } else {
  366. int exitcode = -1;
  367. waitpid(cpid,&exitcode,0);
  368. if (exitcode == 0) {
  369. _ips.insert(ip);
  370. return true;
  371. } else return false;
  372. }
  373. return false;
  374. }
  375. #endif // __LINUX__
  376. #ifdef __APPLE__
  377. static bool ___removeIp(const char *_dev,const InetAddress &ip)
  378. {
  379. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  380. if (!ifconfig)
  381. return false;
  382. long cpid;
  383. if ((cpid = (long)vfork()) == 0) {
  384. execl(ifconfig,ifconfig,_dev,"inet",ip.toIpString().c_str(),"-alias",(const char *)0);
  385. _exit(-1);
  386. } else {
  387. int exitcode = -1;
  388. waitpid(cpid,&exitcode,0);
  389. return (exitcode == 0);
  390. }
  391. return false; // never reached, make compiler shut up about return value
  392. }
  393. bool EthernetTap::addIP(const InetAddress &ip)
  394. {
  395. const char *ifconfig = UNIX_COMMANDS[ZT_UNIX_IFCONFIG_COMMAND];
  396. if (!ifconfig) {
  397. LOG("ERROR: could not configure IP address for %s: unable to find 'ifconfig' command on system (checked /sbin, /bin, /usr/sbin, /usr/bin)",_dev);
  398. return false;
  399. }
  400. Mutex::Lock _l(_ips_m);
  401. if (!ip)
  402. return false;
  403. if (_ips.count(ip) > 0)
  404. return true; // IP/netmask already assigned
  405. // Remove and reconfigure if address is the same but netmask is different
  406. for(std::set<InetAddress>::iterator i(_ips.begin());i!=_ips.end();++i) {
  407. if ((i->ipsEqual(ip))&&(i->netmaskBits() != ip.netmaskBits())) {
  408. if (___removeIp(_dev,*i)) {
  409. _ips.erase(i);
  410. break;
  411. } else {
  412. LOG("WARNING: failed to remove old IP/netmask %s to replace with %s",i->toString().c_str(),ip.toString().c_str());
  413. }
  414. }
  415. }
  416. long cpid;
  417. if ((cpid = (long)vfork()) == 0) {
  418. execl(ifconfig,ifconfig,_dev,ip.isV4() ? "inet" : "inet6",ip.toString().c_str(),"alias",(const char *)0);
  419. _exit(-1);
  420. } else {
  421. int exitcode = -1;
  422. waitpid(cpid,&exitcode,0);
  423. if (exitcode == 0) {
  424. _ips.insert(ip);
  425. return true;
  426. }
  427. }
  428. return false;
  429. }
  430. #endif // __APPLE__
  431. bool EthernetTap::removeIP(const InetAddress &ip)
  432. {
  433. Mutex::Lock _l(_ips_m);
  434. if (_ips.count(ip) > 0) {
  435. if (___removeIp(_dev,ip)) {
  436. _ips.erase(ip);
  437. return true;
  438. }
  439. }
  440. return false;
  441. }
  442. void EthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  443. {
  444. char putBuf[4096 + 14];
  445. if ((_fd > 0)&&(len <= _mtu)) {
  446. for(int i=0;i<6;++i)
  447. putBuf[i] = to.data[i];
  448. for(int i=0;i<6;++i)
  449. putBuf[i+6] = from.data[i];
  450. *((uint16_t *)(putBuf + 12)) = htons((uint16_t)etherType);
  451. memcpy(putBuf + 14,data,len);
  452. len += 14;
  453. int n = ::write(_fd,putBuf,len);
  454. if (n <= 0) {
  455. LOG("error writing packet to Ethernet tap device: %s",strerror(errno));
  456. } else if (n != (int)len) {
  457. // Saw this gremlin once, so log it if we see it again... OSX tap
  458. // or something seems to have goofy issues with certain MTUs.
  459. LOG("ERROR: write underrun: %s tap write() wrote %d of %u bytes of frame",_dev,n,len);
  460. }
  461. }
  462. }
  463. std::string EthernetTap::deviceName() const
  464. {
  465. return std::string(_dev);
  466. }
  467. #ifdef __LINUX__
  468. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  469. {
  470. char *ptr,*ptr2;
  471. unsigned char mac[6];
  472. std::set<MulticastGroup> newGroups;
  473. int fd = ::open("/proc/net/dev_mcast",O_RDONLY);
  474. if (fd > 0) {
  475. char buf[131072];
  476. int n = (int)::read(fd,buf,sizeof(buf));
  477. if ((n > 0)&&(n < (int)sizeof(buf))) {
  478. buf[n] = (char)0;
  479. for(char *l=strtok_r(buf,"\r\n",&ptr);(l);l=strtok_r((char *)0,"\r\n",&ptr)) {
  480. int fno = 0;
  481. char *devname = (char *)0;
  482. char *mcastmac = (char *)0;
  483. for(char *f=strtok_r(l," \t",&ptr2);(f);f=strtok_r((char *)0," \t",&ptr2)) {
  484. if (fno == 1)
  485. devname = f;
  486. else if (fno == 4)
  487. mcastmac = f;
  488. ++fno;
  489. }
  490. if ((devname)&&(!strcmp(devname,_dev))&&(mcastmac)&&(Utils::unhex(mcastmac,mac,6) == 6))
  491. newGroups.insert(MulticastGroup(MAC(mac),0));
  492. }
  493. }
  494. ::close(fd);
  495. }
  496. {
  497. Mutex::Lock _l(_ips_m);
  498. for(std::set<InetAddress>::const_iterator i(_ips.begin());i!=_ips.end();++i)
  499. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  500. }
  501. bool changed = false;
  502. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  503. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  504. if (!groups.count(*mg)) {
  505. groups.insert(*mg);
  506. changed = true;
  507. }
  508. }
  509. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  510. if (!newGroups.count(*mg)) {
  511. groups.erase(mg++);
  512. changed = true;
  513. } else ++mg;
  514. }
  515. return changed;
  516. }
  517. #endif // __LINUX__
  518. #ifdef __APPLE__
  519. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  520. {
  521. std::set<MulticastGroup> newGroups;
  522. struct ifmaddrs *ifmap = (struct ifmaddrs *)0;
  523. if (!getifmaddrs(&ifmap)) {
  524. struct ifmaddrs *p = ifmap;
  525. while (p) {
  526. if (p->ifma_addr->sa_family == AF_LINK) {
  527. struct sockaddr_dl *in = (struct sockaddr_dl *)p->ifma_name;
  528. struct sockaddr_dl *la = (struct sockaddr_dl *)p->ifma_addr;
  529. if ((la->sdl_alen == 6)&&(in->sdl_nlen <= sizeof(_dev))&&(!memcmp(_dev,in->sdl_data,in->sdl_nlen)))
  530. newGroups.insert(MulticastGroup(MAC(la->sdl_data + la->sdl_nlen),0));
  531. }
  532. p = p->ifma_next;
  533. }
  534. freeifmaddrs(ifmap);
  535. }
  536. {
  537. Mutex::Lock _l(_ips_m);
  538. for(std::set<InetAddress>::const_iterator i(_ips.begin());i!=_ips.end();++i)
  539. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  540. }
  541. bool changed = false;
  542. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  543. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  544. if (!groups.count(*mg)) {
  545. groups.insert(*mg);
  546. changed = true;
  547. }
  548. }
  549. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  550. if (!newGroups.count(*mg)) {
  551. groups.erase(mg++);
  552. changed = true;
  553. } else ++mg;
  554. }
  555. return changed;
  556. }
  557. #endif // __APPLE__
  558. void EthernetTap::threadMain()
  559. throw()
  560. {
  561. fd_set readfds,nullfds;
  562. MAC to,from;
  563. char getBuf[4096 + 14];
  564. Buffer<4096> data;
  565. // Wait for a moment after startup -- wait for Network to finish
  566. // constructing itself.
  567. Thread::sleep(500);
  568. FD_ZERO(&readfds);
  569. FD_ZERO(&nullfds);
  570. int nfds = (int)std::max(_shutdownSignalPipe[0],_fd) + 1;
  571. for(;;) {
  572. FD_SET(_shutdownSignalPipe[0],&readfds);
  573. FD_SET(_fd,&readfds);
  574. select(nfds,&readfds,&nullfds,&nullfds,(struct timeval *)0);
  575. if (FD_ISSET(_shutdownSignalPipe[0],&readfds)) // writes to shutdown pipe terminate thread
  576. break;
  577. if (FD_ISSET(_fd,&readfds)) {
  578. int n = (int)::read(_fd,getBuf,_mtu + 14);
  579. if (n > 14) {
  580. for(int i=0;i<6;++i)
  581. to.data[i] = (unsigned char)getBuf[i];
  582. for(int i=0;i<6;++i)
  583. from.data[i] = (unsigned char)getBuf[i + 6];
  584. data.copyFrom(getBuf + 14,(unsigned int)n - 14);
  585. _handler(_arg,from,to,ntohs(((const uint16_t *)getBuf)[6]),data);
  586. } else if (n < 0) {
  587. if ((errno != EINTR)&&(errno != ETIMEDOUT)) {
  588. TRACE("unexpected error reading from tap: %s",strerror(errno));
  589. break;
  590. }
  591. }
  592. }
  593. }
  594. }
  595. } // namespace ZeroTier
  596. #endif // __UNIX_LIKE__ //////////////////////////////////////////////////////
  597. #ifdef __WINDOWS__
  598. #include <queue>
  599. #include <WinSock2.h>
  600. #include <Windows.h>
  601. #include <iphlpapi.h>
  602. #include <ws2ipdef.h>
  603. #include <WS2tcpip.h>
  604. #include <tchar.h>
  605. #include <winreg.h>
  606. namespace ZeroTier {
  607. /* Background thread that handles I/O to/from all running
  608. * EthernetTap instances using WinPcap -- this must be
  609. * managed from a single thread because of the need to
  610. * "reboot" npf every time a new interface is added. */
  611. class _WinEthernetTapPcapIOThread
  612. {
  613. public:
  614. _WinEthernetTapPcapIOThread()
  615. {
  616. scManager = OpenSCManager(NULL,NULL,SC_MANAGER_ALL_ACCESS);
  617. if (scManager == NULL)
  618. fprintf(stderr,"ZeroTier One: WARNING: unable to OpenSCManager(), tap will have issues with new devices!\r\n");
  619. updateSem = CreateSemaphore(NULL,0,1,NULL); // binary
  620. run = true;
  621. needReload = false;
  622. thread = Thread::start(this);
  623. }
  624. ~_WinEthernetTapPcapIOThread()
  625. {
  626. run = false;
  627. needReload = false;
  628. ReleaseSemaphore(updateSem,1,NULL);
  629. Thread::join(thread);
  630. CloseHandle(updateSem);
  631. if (scManager != NULL)
  632. CloseServiceHandle(scManager);
  633. }
  634. void threadMain()
  635. throw()
  636. {
  637. HANDLE *objects = new HANDLE[1];
  638. objects[0] = updateSem;
  639. DWORD numObjects = 1;
  640. for(;;) {
  641. if (!run) {
  642. delete [] objects;
  643. return;
  644. }
  645. printf("waiting on: %d\r\n",(int)numObjects);
  646. WaitForMultipleObjects(numObjects,objects,FALSE,INFINITE);
  647. {
  648. Mutex::Lock _l(taps_m);
  649. for(std::list<EthernetTap *>::iterator tapptr(taps.begin());tapptr!=taps.end();++tapptr) {
  650. EthernetTap *tap = *tapptr;
  651. if (tap->_pcap) {
  652. {
  653. Mutex::Lock _l2(tap->_injectPending_m);
  654. while (!tap->_injectPending.empty()) {
  655. pcap_sendpacket(tap->_pcap,(const u_char *)(tap->_injectPending.front().first.data),tap->_injectPending.front().second);
  656. tap->_injectPending.pop();
  657. }
  658. }
  659. printf("dispatch: %s\r\n",tap->_myDeviceInstanceId.c_str());
  660. pcap_dispatch(tap->_pcap,-1,&EthernetTap::_pcapHandler,(u_char *)tap);
  661. }
  662. }
  663. if (needReload) {
  664. // Close all taps and restart WinPcap driver to scan for possible new
  665. // interfaces... yuck. This is done because WinPcap does not support
  666. // hot plug, so if we've added a new loopback adapter it won't show
  667. // up without this full system refresh.
  668. needReload = false;
  669. for(std::list<EthernetTap *>::iterator tapptr(taps.begin());tapptr!=taps.end();++tapptr) {
  670. if ((*tapptr)->_pcap) {
  671. pcap_close((*tapptr)->_pcap);
  672. (*tapptr)->_pcap = (pcap_t *)0;
  673. }
  674. }
  675. if (scManager != NULL) {
  676. Thread::sleep(250);
  677. SC_HANDLE npfService = OpenServiceA(scManager,"npf",SERVICE_ALL_ACCESS);
  678. if (npfService != NULL) {
  679. SERVICE_STATUS sstatus;
  680. memset(&sstatus,0,sizeof(SERVICE_STATUS));
  681. ControlService(npfService,SERVICE_CONTROL_STOP,&sstatus);
  682. printf("service restart\r\n");
  683. CloseServiceHandle(npfService);
  684. }
  685. Thread::sleep(250);
  686. }
  687. delete [] objects;
  688. objects = new HANDLE[taps.size() + 1];
  689. objects[0] = updateSem;
  690. numObjects = 1;
  691. pcap_if_t *alldevs;
  692. char pcaperrbuf[PCAP_ERRBUF_SIZE+1];
  693. if (pcap_findalldevs(&alldevs,pcaperrbuf) != -1) {
  694. for(std::list<EthernetTap *>::iterator tapptr(taps.begin());tapptr!=taps.end();++tapptr) {
  695. EthernetTap *tap = *tapptr;
  696. pcap_if_t *mydev = (pcap_if_t *)0;
  697. for(mydev=alldevs;(mydev);mydev=mydev->next) {
  698. if (strstr(mydev->name,tap->_myDeviceInstanceId.c_str()))
  699. break;
  700. }
  701. if (mydev) {
  702. tap->_pcap = pcap_open_live(mydev->name,65535,1,0,pcaperrbuf);
  703. pcap_setnonblock(tap->_pcap,1,pcaperrbuf);
  704. if (tap->_pcap) {
  705. printf("pcap opened: %s\r\n",mydev->name);
  706. objects[numObjects++] = pcap_getevent(tap->_pcap);
  707. }
  708. } else {
  709. tap->_pcap = (pcap_t *)0;
  710. }
  711. }
  712. pcap_freealldevs(alldevs);
  713. }
  714. }
  715. }
  716. if (!run) {
  717. delete [] objects;
  718. return;
  719. }
  720. }
  721. }
  722. inline void addTap(EthernetTap *t)
  723. {
  724. Mutex::Lock _l(taps_m);
  725. taps.push_back(t);
  726. needReload = true;
  727. ReleaseSemaphore(updateSem,1,NULL);
  728. }
  729. inline void removeTap(EthernetTap *t)
  730. {
  731. Mutex::Lock _l(taps_m);
  732. for(std::list<EthernetTap *>::iterator tapptr(taps.begin());tapptr!=taps.end();++tapptr) {
  733. if (*tapptr == t) {
  734. taps.erase(tapptr);
  735. break;
  736. }
  737. }
  738. needReload = true;
  739. ReleaseSemaphore(updateSem,1,NULL);
  740. }
  741. std::list<EthernetTap *> taps;
  742. Mutex taps_m;
  743. SC_HANDLE scManager;
  744. HANDLE updateSem;
  745. volatile bool run;
  746. volatile bool needReload;
  747. Thread thread;
  748. };
  749. static _WinEthernetTapPcapIOThread _pcapIoThread;
  750. static Mutex _systemTapInitLock;
  751. EthernetTap::EthernetTap(
  752. const RuntimeEnvironment *renv,
  753. const char *tag,
  754. const MAC &mac,
  755. unsigned int mtu,
  756. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  757. void *arg)
  758. throw(std::runtime_error) :
  759. _mac(mac),
  760. _mtu(mtu),
  761. _r(renv),
  762. _handler(handler),
  763. _arg(arg),
  764. _pcap((pcap_t *)0)
  765. {
  766. char subkeyName[1024];
  767. char subkeyClass[1024];
  768. char data[1024];
  769. Mutex::Lock _l(_systemTapInitLock); // only do one at a time, process-wide
  770. HKEY nwAdapters;
  771. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  772. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  773. std::set<std::string> existingDeviceInstances;
  774. // Enumerate all Microsoft Loopback Adapter instances and look for one
  775. // that matches our tag.
  776. for(DWORD subkeyIndex=0;subkeyIndex!=-1;) {
  777. DWORD type;
  778. DWORD dataLen;
  779. DWORD subkeyNameLen = sizeof(subkeyName);
  780. DWORD subkeyClassLen = sizeof(subkeyClass);
  781. FILETIME lastWriteTime;
  782. switch (RegEnumKeyExA(nwAdapters,subkeyIndex++,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime)) {
  783. case ERROR_NO_MORE_ITEMS: subkeyIndex = -1; break;
  784. case ERROR_SUCCESS:
  785. type = 0;
  786. dataLen = sizeof(data);
  787. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  788. data[dataLen] = '\0';
  789. if (!strcmpi(data,"*msloop")) {
  790. std::string instanceId;
  791. type = 0;
  792. dataLen = sizeof(data);
  793. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  794. instanceId.assign(data,dataLen);
  795. existingDeviceInstances.insert(instanceId);
  796. }
  797. if ((_myDeviceInstanceId.length() == 0)&&(instanceId.length() != 0)) {
  798. type = 0;
  799. dataLen = sizeof(data);
  800. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  801. data[dataLen] = '\0';
  802. if (!strcmp(data,tag)) {
  803. type = 0;
  804. dataLen = sizeof(data);
  805. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  806. _myDeviceInstanceId = instanceId;
  807. subkeyIndex = -1; // break outer loop
  808. }
  809. }
  810. }
  811. }
  812. }
  813. }
  814. break;
  815. }
  816. }
  817. // If there is no device, try to create one
  818. if (_myDeviceInstanceId.length() == 0) {
  819. // Execute devcon to install an instance of the Microsoft Loopback Adapter
  820. #ifdef _WIN64
  821. const char *devcon = "\\devcon64.exe";
  822. #else
  823. BOOL f64 = FALSE;
  824. const char *devcon = ((IsWow64Process(GetCurrentProcess(),&f64) == TRUE) ? "\\devcon64.exe" : "\\devcon32.exe");
  825. #endif
  826. char windir[4096];
  827. windir[0] = '\0';
  828. GetWindowsDirectoryA(windir,sizeof(windir));
  829. STARTUPINFOA startupInfo;
  830. startupInfo.cb = sizeof(startupInfo);
  831. PROCESS_INFORMATION processInfo;
  832. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  833. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  834. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + devcon + "\" install " + windir + "\\inf\\netloop.inf *msloop").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  835. RegCloseKey(nwAdapters);
  836. throw std::runtime_error(std::string("unable to find or execute devcon at ")+devcon);
  837. }
  838. WaitForSingleObject(processInfo.hProcess,INFINITE);
  839. CloseHandle(processInfo.hProcess);
  840. CloseHandle(processInfo.hThread);
  841. // Scan for that new instance by looking for adapters of type
  842. // *msloop that we did not already see on the first scan.
  843. for(DWORD subkeyIndex=0;subkeyIndex!=-1;) {
  844. DWORD type;
  845. DWORD dataLen;
  846. DWORD subkeyNameLen = sizeof(subkeyName);
  847. DWORD subkeyClassLen = sizeof(subkeyClass);
  848. FILETIME lastWriteTime;
  849. switch (RegEnumKeyExA(nwAdapters,subkeyIndex++,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime)) {
  850. case ERROR_NO_MORE_ITEMS: subkeyIndex = -1; break;
  851. case ERROR_SUCCESS:
  852. type = 0;
  853. dataLen = sizeof(data);
  854. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  855. data[dataLen] = '\0';
  856. if (!strcmpi(data,"*msloop")) {
  857. type = 0;
  858. dataLen = sizeof(data);
  859. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  860. if (existingDeviceInstances.count(std::string(data,dataLen)) == 0) {
  861. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,strlen(tag)+1);
  862. _myDeviceInstanceId.assign(data,dataLen);
  863. subkeyIndex = -1; // break outer loop
  864. }
  865. }
  866. }
  867. }
  868. break;
  869. }
  870. }
  871. }
  872. RegCloseKey(nwAdapters);
  873. if (_myDeviceInstanceId.length() == 0)
  874. throw std::runtime_error("unable to create new loopback adapter for tap");
  875. // pcap is opened and managed by the pcap I/O thread
  876. _pcapIoThread.addTap(this);
  877. }
  878. EthernetTap::~EthernetTap()
  879. {
  880. _pcapIoThread.removeTap(this);
  881. if (_pcap)
  882. pcap_close(_pcap);
  883. }
  884. void EthernetTap::whack()
  885. {
  886. }
  887. bool EthernetTap::addIP(const InetAddress &ip)
  888. {
  889. return false;
  890. }
  891. bool EthernetTap::removeIP(const InetAddress &ip)
  892. {
  893. return false;
  894. }
  895. void EthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  896. {
  897. if (len > (ZT_IF_MTU))
  898. return;
  899. {
  900. Mutex::Lock _l(_injectPending_m);
  901. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  902. char *d = _injectPending.back().first.data;
  903. memcpy(d,to.data,6);
  904. memcpy(d + 6,from.data,6);
  905. *((uint16_t *)(d + 12)) = Utils::hton(etherType);
  906. memcpy(d + 14,data,len);
  907. }
  908. ReleaseSemaphore(_pcapIoThread.updateSem,1,NULL);
  909. }
  910. std::string EthernetTap::deviceName() const
  911. {
  912. return _myDeviceInstanceId;
  913. }
  914. bool EthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  915. {
  916. // TODO
  917. return false;
  918. }
  919. void EthernetTap::_pcapHandler(u_char *user,const struct pcap_pkthdr *pkt_header,const u_char *pkt_data)
  920. {
  921. printf("got packet: %d\r\n",(int)pkt_header->len);
  922. if (pkt_header->len > 14)
  923. ((EthernetTap *)user)->_handler(((EthernetTap *)user)->_arg,MAC(pkt_data + 6),MAC(pkt_data),Utils::ntoh(*((const uint16_t *)(pkt_data + 12))),Buffer<4096>(pkt_data + 14,pkt_header->len - 14));
  924. }
  925. } // namespace ZeroTier
  926. #endif // __WINDOWS__