WindowsEthernetTap.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. /*
  2. * ZeroTier One - Global Peer to Peer Ethernet
  3. * Copyright (C) 2011-2014 ZeroTier Networks LLC
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * ZeroTier may be used and distributed under the terms of the GPLv3, which
  21. * are available at: http://www.gnu.org/licenses/gpl-3.0.html
  22. *
  23. * If you would like to embed ZeroTier into a commercial application or
  24. * redistribute it in a modified binary form, please contact ZeroTier Networks
  25. * LLC. Start here: http://www.zerotier.com/
  26. */
  27. #include <stdio.h>
  28. #include <stdlib.h>
  29. #include <stdint.h>
  30. #include <string.h>
  31. #include <WinSock2.h>
  32. #include <Windows.h>
  33. #include <tchar.h>
  34. #include <winreg.h>
  35. #include <wchar.h>
  36. #include <ws2ipdef.h>
  37. #include <WS2tcpip.h>
  38. #include <IPHlpApi.h>
  39. #include <nldef.h>
  40. #include <netioapi.h>
  41. #include "../node/Constants.hpp"
  42. #include "WindowsEthernetTap.hpp"
  43. #include "WindowsEthernetTapFactory.hpp"
  44. #include "../node/Utils.hpp"
  45. #include "../node/Mutex.hpp"
  46. #include "..\windows\TapDriver\tap-windows.h"
  47. // ff:ff:ff:ff:ff:ff with no ADI
  48. static const ZeroTier::MulticastGroup _blindWildcardMulticastGroup(ZeroTier::MAC(0xff),0);
  49. namespace ZeroTier {
  50. // Only create or delete devices one at a time
  51. static Mutex _systemTapInitLock;
  52. static void _syncIpsWithRegistry(const std::set<InetAddress> &haveIps,const std::string netCfgInstanceId)
  53. {
  54. // Update registry to contain all non-link-local IPs for this interface
  55. std::string regMultiIps,regMultiNetmasks;
  56. for(std::set<InetAddress>::const_iterator i(haveIps.begin());i!=haveIps.end();++i) {
  57. if (!i->isLinkLocal()) {
  58. regMultiIps.append(i->toIpString());
  59. regMultiIps.push_back((char)0);
  60. regMultiNetmasks.append(i->netmask().toIpString());
  61. regMultiNetmasks.push_back((char)0);
  62. }
  63. }
  64. HKEY tcpIpInterfaces;
  65. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  66. if (regMultiIps.length()) {
  67. regMultiIps.push_back((char)0);
  68. regMultiNetmasks.push_back((char)0);
  69. RegSetKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"IPAddress",REG_MULTI_SZ,regMultiIps.data(),(DWORD)regMultiIps.length());
  70. RegSetKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"SubnetMask",REG_MULTI_SZ,regMultiNetmasks.data(),(DWORD)regMultiNetmasks.length());
  71. } else {
  72. RegDeleteKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"IPAddress");
  73. RegDeleteKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"SubnetMask");
  74. }
  75. }
  76. RegCloseKey(tcpIpInterfaces);
  77. }
  78. WindowsEthernetTap::WindowsEthernetTap(
  79. const char *pathToHelpers,
  80. const MAC &mac,
  81. unsigned int mtu,
  82. unsigned int metric,
  83. uint64_t nwid,
  84. const char *desiredDevice,
  85. const char *friendlyName,
  86. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  87. void *arg) :
  88. EthernetTap("WindowsEthernetTap",mac,mtu,metric),
  89. _handler(handler),
  90. _arg(arg),
  91. _tap(INVALID_HANDLE_VALUE),
  92. _injectSemaphore(INVALID_HANDLE_VALUE),
  93. _pathToHelpers(pathToHelpers),
  94. _run(true),
  95. _initialized(false),
  96. _enabled(true)
  97. {
  98. char subkeyName[4096];
  99. char subkeyClass[4096];
  100. char data[4096];
  101. char tag[24];
  102. if (mtu > 2800)
  103. throw std::runtime_error("MTU too large for Windows tap");
  104. Mutex::Lock _l(_systemTapInitLock);
  105. HKEY nwAdapters;
  106. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  107. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  108. std::set<std::string> existingDeviceInstances;
  109. std::string mySubkeyName;
  110. // We "tag" registry entries with the network ID to identify persistent devices
  111. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)nwid);
  112. // Look for the tap instance that corresponds with this network
  113. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  114. DWORD type;
  115. DWORD dataLen;
  116. DWORD subkeyNameLen = sizeof(subkeyName);
  117. DWORD subkeyClassLen = sizeof(subkeyClass);
  118. FILETIME lastWriteTime;
  119. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  120. type = 0;
  121. dataLen = sizeof(data);
  122. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  123. data[dataLen] = '\0';
  124. if (!strnicmp(data,"zttap",5)) {
  125. std::string instanceId;
  126. type = 0;
  127. dataLen = sizeof(data);
  128. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  129. instanceId.assign(data,dataLen);
  130. existingDeviceInstances.insert(instanceId);
  131. }
  132. std::string instanceIdPath;
  133. type = 0;
  134. dataLen = sizeof(data);
  135. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  136. instanceIdPath.assign(data,dataLen);
  137. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  138. type = 0;
  139. dataLen = sizeof(data);
  140. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  141. data[dataLen] = '\0';
  142. if (!strcmp(data,tag)) {
  143. _netCfgInstanceId = instanceId;
  144. _deviceInstanceId = instanceIdPath;
  145. mySubkeyName = subkeyName;
  146. break; // found it!
  147. }
  148. }
  149. }
  150. }
  151. }
  152. } else break; // no more subkeys or error occurred enumerating them
  153. }
  154. // If there is no device, try to create one
  155. if (_netCfgInstanceId.length() == 0) {
  156. // Log devcon output to a file
  157. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  158. if (devconLog != INVALID_HANDLE_VALUE)
  159. SetFilePointer(devconLog,0,0,FILE_END);
  160. // Execute devcon to install an instance of the Microsoft Loopback Adapter
  161. STARTUPINFOA startupInfo;
  162. startupInfo.cb = sizeof(startupInfo);
  163. if (devconLog != INVALID_HANDLE_VALUE) {
  164. SetFilePointer(devconLog,0,0,FILE_END);
  165. startupInfo.hStdOutput = devconLog;
  166. startupInfo.hStdError = devconLog;
  167. }
  168. PROCESS_INFORMATION processInfo;
  169. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  170. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  171. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" install \"" + _pathToHelpers + WindowsEthernetTapFactory::WINENV.tapDriver + "\" zttap200").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  172. RegCloseKey(nwAdapters);
  173. if (devconLog != INVALID_HANDLE_VALUE)
  174. CloseHandle(devconLog);
  175. throw std::runtime_error(std::string("unable to find or execute devcon at ") + WindowsEthernetTapFactory::WINENV.devcon);
  176. }
  177. WaitForSingleObject(processInfo.hProcess,INFINITE);
  178. CloseHandle(processInfo.hProcess);
  179. CloseHandle(processInfo.hThread);
  180. if (devconLog != INVALID_HANDLE_VALUE)
  181. CloseHandle(devconLog);
  182. // Scan for the new instance by simply looking for taps that weren't originally there...
  183. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  184. DWORD type;
  185. DWORD dataLen;
  186. DWORD subkeyNameLen = sizeof(subkeyName);
  187. DWORD subkeyClassLen = sizeof(subkeyClass);
  188. FILETIME lastWriteTime;
  189. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  190. type = 0;
  191. dataLen = sizeof(data);
  192. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  193. data[dataLen] = '\0';
  194. if (!strnicmp(data,"zttap",5)) {
  195. type = 0;
  196. dataLen = sizeof(data);
  197. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  198. if (existingDeviceInstances.count(std::string(data,dataLen)) == 0) {
  199. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  200. _netCfgInstanceId.assign(data,dataLen);
  201. type = 0;
  202. dataLen = sizeof(data);
  203. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  204. _deviceInstanceId.assign(data,dataLen);
  205. mySubkeyName = subkeyName;
  206. // Disable DHCP by default on newly created devices
  207. HKEY tcpIpInterfaces;
  208. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  209. DWORD enable = 0;
  210. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  211. RegCloseKey(tcpIpInterfaces);
  212. }
  213. break; // found it!
  214. }
  215. }
  216. }
  217. }
  218. } else break; // no more keys or error occurred
  219. }
  220. }
  221. if (_netCfgInstanceId.length() > 0) {
  222. char tmps[64];
  223. unsigned int tmpsl = Utils::snprintf(tmps,sizeof(tmps),"%.2X-%.2X-%.2X-%.2X-%.2X-%.2X",(unsigned int)mac[0],(unsigned int)mac[1],(unsigned int)mac[2],(unsigned int)mac[3],(unsigned int)mac[4],(unsigned int)mac[5]) + 1;
  224. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  225. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  226. DWORD tmp = mtu;
  227. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MTU",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  228. tmp = 0;
  229. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp)); // disable DHCP by default on new devices
  230. RegCloseKey(nwAdapters);
  231. } else {
  232. RegCloseKey(nwAdapters);
  233. throw std::runtime_error("unable to find or create tap adapter");
  234. }
  235. // Convert device GUID junk... blech... is there an easier way to do this?
  236. {
  237. char nobraces[128];
  238. const char *nbtmp1 = _netCfgInstanceId.c_str();
  239. char *nbtmp2 = nobraces;
  240. while (*nbtmp1) {
  241. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  242. *nbtmp2++ = *nbtmp1;
  243. ++nbtmp1;
  244. }
  245. *nbtmp2 = (char)0;
  246. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  247. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  248. }
  249. // Look up interface LUID... why are there (at least) four fucking ways to refer to a network device in Windows?
  250. if (ConvertInterfaceGuidToLuid(&_deviceGuid,&_deviceLuid) != NO_ERROR)
  251. throw std::runtime_error("unable to convert device interface GUID to LUID");
  252. if (friendlyName)
  253. setFriendlyName(friendlyName);
  254. // Start background thread that actually performs I/O
  255. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  256. _thread = Thread::start(this);
  257. // Certain functions can now work (e.g. ips())
  258. _initialized = true;
  259. }
  260. WindowsEthernetTap::~WindowsEthernetTap()
  261. {
  262. _run = false;
  263. ReleaseSemaphore(_injectSemaphore,1,NULL);
  264. Thread::join(_thread);
  265. CloseHandle(_injectSemaphore);
  266. _disableTapDevice();
  267. }
  268. void WindowsEthernetTap::setEnabled(bool en)
  269. {
  270. _enabled = en;
  271. }
  272. bool WindowsEthernetTap::enabled() const
  273. {
  274. return _enabled;
  275. }
  276. bool WindowsEthernetTap::addIP(const InetAddress &ip)
  277. {
  278. if (!_initialized)
  279. return false;
  280. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  281. return false;
  282. std::set<InetAddress> haveIps(ips());
  283. try {
  284. // Add IP to interface at the netlink level if not already assigned.
  285. if (!haveIps.count(ip)) {
  286. MIB_UNICASTIPADDRESS_ROW ipr;
  287. InitializeUnicastIpAddressEntry(&ipr);
  288. if (ip.isV4()) {
  289. ipr.Address.Ipv4.sin_family = AF_INET;
  290. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)ip.rawIpData());
  291. ipr.OnLinkPrefixLength = ip.port();
  292. if (ipr.OnLinkPrefixLength >= 32)
  293. return false;
  294. } else if (ip.isV6()) {
  295. ipr.Address.Ipv6.sin6_family = AF_INET6;
  296. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,ip.rawIpData(),16);
  297. ipr.OnLinkPrefixLength = ip.port();
  298. if (ipr.OnLinkPrefixLength >= 128)
  299. return false;
  300. } else return false;
  301. ipr.PrefixOrigin = IpPrefixOriginManual;
  302. ipr.SuffixOrigin = IpSuffixOriginManual;
  303. ipr.ValidLifetime = 0xffffffff;
  304. ipr.PreferredLifetime = 0xffffffff;
  305. ipr.InterfaceLuid = _deviceLuid;
  306. ipr.InterfaceIndex = _getDeviceIndex();
  307. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  308. haveIps.insert(ip);
  309. } else {
  310. return false;
  311. }
  312. }
  313. _syncIpsWithRegistry(haveIps,_netCfgInstanceId);
  314. } catch ( ... ) {
  315. return false;
  316. }
  317. return true;
  318. }
  319. bool WindowsEthernetTap::removeIP(const InetAddress &ip)
  320. {
  321. if (!_initialized)
  322. return false;
  323. try {
  324. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  325. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  326. for(DWORD i=0;i<ipt->NumEntries;++i) {
  327. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  328. InetAddress addr;
  329. switch(ipt->Table[i].Address.si_family) {
  330. case AF_INET:
  331. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  332. break;
  333. case AF_INET6:
  334. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  335. if (addr.isLinkLocal())
  336. continue; // can't remove link-local IPv6 addresses
  337. break;
  338. }
  339. if (addr == ip) {
  340. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  341. FreeMibTable(ipt);
  342. _syncIpsWithRegistry(ips(),_netCfgInstanceId);
  343. return true;
  344. }
  345. }
  346. }
  347. FreeMibTable((PVOID)ipt);
  348. }
  349. } catch ( ... ) {}
  350. return false;
  351. }
  352. std::set<InetAddress> WindowsEthernetTap::ips() const
  353. {
  354. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  355. std::set<InetAddress> addrs;
  356. if (!_initialized)
  357. return addrs;
  358. try {
  359. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  360. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  361. for(DWORD i=0;i<ipt->NumEntries;++i) {
  362. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  363. switch(ipt->Table[i].Address.si_family) {
  364. case AF_INET: {
  365. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  366. if (ip != InetAddress::LO4)
  367. addrs.insert(ip);
  368. } break;
  369. case AF_INET6: {
  370. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  371. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  372. addrs.insert(ip);
  373. } break;
  374. }
  375. }
  376. }
  377. FreeMibTable(ipt);
  378. }
  379. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  380. return addrs;
  381. }
  382. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  383. {
  384. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > (ZT_IF_MTU)))
  385. return;
  386. Mutex::Lock _l(_injectPending_m);
  387. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  388. char *d = _injectPending.back().first.data;
  389. to.copyTo(d,6);
  390. from.copyTo(d + 6,6);
  391. d[12] = (char)((etherType >> 8) & 0xff);
  392. d[13] = (char)(etherType & 0xff);
  393. memcpy(d + 14,data,len);
  394. ReleaseSemaphore(_injectSemaphore,1,NULL);
  395. }
  396. std::string WindowsEthernetTap::deviceName() const
  397. {
  398. char tmp[1024];
  399. if (ConvertInterfaceLuidToNameA(&_deviceLuid,tmp,sizeof(tmp)) != NO_ERROR)
  400. return std::string("[ConvertInterfaceLuidToName() failed]");
  401. return std::string(tmp);
  402. }
  403. void WindowsEthernetTap::setFriendlyName(const char *dn)
  404. {
  405. if (!_initialized)
  406. return;
  407. HKEY ifp;
  408. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,(std::string("SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\") + _netCfgInstanceId).c_str(),0,KEY_READ|KEY_WRITE,&ifp) == ERROR_SUCCESS) {
  409. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  410. RegCloseKey(ifp);
  411. }
  412. }
  413. bool WindowsEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  414. {
  415. if (!_initialized)
  416. return false;
  417. HANDLE t = _tap;
  418. if (t == INVALID_HANDLE_VALUE)
  419. return false;
  420. std::set<MulticastGroup> newGroups;
  421. // Ensure that groups are added for each IP... this handles the MAC:ADI
  422. // groups that are created from IPv4 addresses. Some of these may end
  423. // up being duplicates of what the IOCTL returns but that's okay since
  424. // the set<> will filter that.
  425. std::set<InetAddress> ipaddrs(ips());
  426. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  427. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  428. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  429. // level... something Windows does not seem to expose ordinarily. This lets
  430. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  431. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  432. DWORD bytesReturned = 0;
  433. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  434. MAC mac;
  435. DWORD i = 0;
  436. while ((i + 6) <= bytesReturned) {
  437. mac.setTo(mcastbuf + i,6);
  438. i += 6;
  439. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  440. // exclude the nulls that may be returned or any other junk Windows puts in there
  441. newGroups.insert(MulticastGroup(mac,0));
  442. }
  443. }
  444. }
  445. bool changed = false;
  446. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  447. if (!groups.count(*mg)) {
  448. groups.insert(*mg);
  449. changed = true;
  450. }
  451. }
  452. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  453. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  454. groups.erase(mg++);
  455. changed = true;
  456. } else ++mg;
  457. }
  458. return changed;
  459. }
  460. bool WindowsEthernetTap::createPseudoDefaultRoute() const
  461. {
  462. return true;
  463. }
  464. void WindowsEthernetTap::threadMain()
  465. throw()
  466. {
  467. char tapPath[256];
  468. OVERLAPPED tapOvlRead,tapOvlWrite;
  469. HANDLE wait4[3];
  470. char *tapReadBuf = (char *)0;
  471. // Shouldn't be needed, but Windows does not overcommit. This Windows
  472. // tap code is defensive to schizoid paranoia degrees.
  473. while (!tapReadBuf) {
  474. tapReadBuf = (char *)::malloc(ZT_IF_MTU + 32);
  475. if (!tapReadBuf)
  476. Sleep(1000);
  477. }
  478. // Tap is in this weird Windows global pseudo file space
  479. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  480. // More insanity: repetatively try to enable/disable tap device. The first
  481. // time we succeed, close it and do it again. This is to fix a driver init
  482. // bug that seems to be extremely non-deterministic and to only occur after
  483. // headless MSI upgrade. It cannot be reproduced in any other circumstance.
  484. bool throwOneAway = true;
  485. while (_run) {
  486. _disableTapDevice();
  487. Sleep(250);
  488. if (!_enableTapDevice()) {
  489. ::free(tapReadBuf);
  490. _enabled = false;
  491. return; // only happens if devcon is missing or totally fails
  492. }
  493. Sleep(250);
  494. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  495. if (_tap == INVALID_HANDLE_VALUE) {
  496. Sleep(500);
  497. continue;
  498. }
  499. uint32_t tmpi = 1;
  500. DWORD bytesReturned = 0;
  501. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  502. if (throwOneAway) {
  503. throwOneAway = false;
  504. CloseHandle(_tap);
  505. _tap = INVALID_HANDLE_VALUE;
  506. Sleep(250);
  507. continue;
  508. } else break;
  509. }
  510. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  511. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  512. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  513. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  514. wait4[0] = _injectSemaphore;
  515. wait4[1] = tapOvlRead.hEvent;
  516. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  517. // Start overlapped read, which is always active
  518. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  519. bool writeInProgress = false;
  520. for(;;) {
  521. if (!_run) break;
  522. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,5000,TRUE);
  523. if (!_run) break;
  524. if ((r == WAIT_TIMEOUT)||(r == WAIT_FAILED))
  525. continue;
  526. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  527. DWORD bytesRead = 0;
  528. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  529. if ((bytesRead > 14)&&(_enabled)) {
  530. MAC to(tapReadBuf,6);
  531. MAC from(tapReadBuf + 6,6);
  532. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  533. try {
  534. Buffer<4096> tmp(tapReadBuf + 14,bytesRead - 14);
  535. _handler(_arg,from,to,etherType,tmp);
  536. } catch ( ... ) {} // handlers should not throw
  537. }
  538. }
  539. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  540. }
  541. if (writeInProgress) {
  542. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  543. writeInProgress = false;
  544. _injectPending_m.lock();
  545. _injectPending.pop();
  546. } else continue; // still writing, so skip code below and wait
  547. } else _injectPending_m.lock();
  548. if (!_injectPending.empty()) {
  549. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  550. writeInProgress = true;
  551. }
  552. _injectPending_m.unlock();
  553. }
  554. CancelIo(_tap);
  555. CloseHandle(tapOvlRead.hEvent);
  556. CloseHandle(tapOvlWrite.hEvent);
  557. CloseHandle(_tap);
  558. _tap = INVALID_HANDLE_VALUE;
  559. ::free(tapReadBuf);
  560. }
  561. bool WindowsEthernetTap::_disableTapDevice()
  562. {
  563. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  564. if (devconLog != INVALID_HANDLE_VALUE)
  565. SetFilePointer(devconLog,0,0,FILE_END);
  566. STARTUPINFOA startupInfo;
  567. startupInfo.cb = sizeof(startupInfo);
  568. if (devconLog != INVALID_HANDLE_VALUE) {
  569. startupInfo.hStdOutput = devconLog;
  570. startupInfo.hStdError = devconLog;
  571. }
  572. PROCESS_INFORMATION processInfo;
  573. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  574. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  575. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" disable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  576. if (devconLog != INVALID_HANDLE_VALUE)
  577. CloseHandle(devconLog);
  578. return false;
  579. }
  580. WaitForSingleObject(processInfo.hProcess,INFINITE);
  581. CloseHandle(processInfo.hProcess);
  582. CloseHandle(processInfo.hThread);
  583. if (devconLog != INVALID_HANDLE_VALUE)
  584. CloseHandle(devconLog);
  585. return true;
  586. }
  587. bool WindowsEthernetTap::_enableTapDevice()
  588. {
  589. HANDLE devconLog = CreateFileA((_pathToHelpers + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  590. if (devconLog != INVALID_HANDLE_VALUE)
  591. SetFilePointer(devconLog,0,0,FILE_END);
  592. STARTUPINFOA startupInfo;
  593. startupInfo.cb = sizeof(startupInfo);
  594. if (devconLog != INVALID_HANDLE_VALUE) {
  595. startupInfo.hStdOutput = devconLog;
  596. startupInfo.hStdError = devconLog;
  597. }
  598. PROCESS_INFORMATION processInfo;
  599. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  600. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  601. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _pathToHelpers + WindowsEthernetTapFactory::WINENV.devcon + "\" enable @" + _deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  602. if (devconLog != INVALID_HANDLE_VALUE)
  603. CloseHandle(devconLog);
  604. return false;
  605. }
  606. WaitForSingleObject(processInfo.hProcess,INFINITE);
  607. CloseHandle(processInfo.hProcess);
  608. CloseHandle(processInfo.hThread);
  609. if (devconLog != INVALID_HANDLE_VALUE)
  610. CloseHandle(devconLog);
  611. return true;
  612. }
  613. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  614. {
  615. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  616. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  617. throw std::runtime_error("GetIfTable2Ex() failed");
  618. for(ULONG i=0;i<ift->NumEntries;++i) {
  619. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  620. FreeMibTable(ift);
  621. return ift->Table[i].InterfaceIndex;
  622. }
  623. }
  624. FreeMibTable(&ift);
  625. throw std::runtime_error("interface not found");
  626. }
  627. } // namespace ZeroTier