WindowsEthernetTap.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836
  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 "../node/EthernetTap.hpp"
  43. #include "../node/Utils.hpp"
  44. #include "../node/Mutex.hpp"
  45. #include "WindowsEthernetTap.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. // Helper function to get an adapter's LUID and index from its GUID. The LUID is
  51. // constant but the index can change, so go ahead and just look them both up by
  52. // the GUID which is constant. (The GUID is the instance ID in the registry.)
  53. static inline std::pair<NET_LUID,NET_IFINDEX> _findAdapterByGuid(const GUID &guid)
  54. throw(std::runtime_error)
  55. {
  56. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  57. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  58. throw std::runtime_error("GetIfTable2Ex() failed");
  59. for(ULONG i=0;i<ift->NumEntries;++i) {
  60. if (ift->Table[i].InterfaceGuid == guid) {
  61. std::pair<NET_LUID,NET_IFINDEX> tmp(ift->Table[i].InterfaceLuid,ift->Table[i].InterfaceIndex);
  62. FreeMibTable(ift);
  63. return tmp;
  64. }
  65. }
  66. FreeMibTable(&ift);
  67. throw std::runtime_error("interface not found");
  68. }
  69. // Only create or delete devices one at a time
  70. static Mutex _systemTapInitLock;
  71. // Compute some basic environment stuff on startup
  72. class _WinSysEnv
  73. {
  74. public:
  75. _WinSysEnv()
  76. {
  77. #ifdef _WIN64
  78. is64Bit = TRUE;
  79. devcon = "\\devcon_x64.exe";
  80. tapDriver = "\\tap-windows\\x64\\zttap200.inf";
  81. #else
  82. is64Bit = FALSE;
  83. IsWow64Process(GetCurrentProcess(),&is64Bit);
  84. devcon = ((is64Bit == TRUE) ? "\\devcon_x64.exe" : "\\devcon_x86.exe");
  85. tapDriver = ((is64Bit == TRUE) ? "\\tap-windows\\x64\\zttap200.inf" : "\\tap-windows\\x86\\zttap200.inf");
  86. #endif
  87. }
  88. BOOL is64Bit;
  89. const char *devcon;
  90. const char *tapDriver;
  91. };
  92. static const _WinSysEnv _winEnv;
  93. static bool _disableTapDevice(const RuntimeEnvironment *_r,const std::string deviceInstanceId)
  94. {
  95. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  96. if (devconLog != INVALID_HANDLE_VALUE)
  97. SetFilePointer(devconLog,0,0,FILE_END);
  98. STARTUPINFOA startupInfo;
  99. startupInfo.cb = sizeof(startupInfo);
  100. if (devconLog != INVALID_HANDLE_VALUE) {
  101. startupInfo.hStdOutput = devconLog;
  102. startupInfo.hStdError = devconLog;
  103. }
  104. PROCESS_INFORMATION processInfo;
  105. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  106. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  107. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" disable @" + deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  108. if (devconLog != INVALID_HANDLE_VALUE)
  109. CloseHandle(devconLog);
  110. return false;
  111. }
  112. WaitForSingleObject(processInfo.hProcess,INFINITE);
  113. CloseHandle(processInfo.hProcess);
  114. CloseHandle(processInfo.hThread);
  115. if (devconLog != INVALID_HANDLE_VALUE)
  116. CloseHandle(devconLog);
  117. return true;
  118. }
  119. static bool _enableTapDevice(const RuntimeEnvironment *_r,const std::string deviceInstanceId)
  120. {
  121. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  122. if (devconLog != INVALID_HANDLE_VALUE)
  123. SetFilePointer(devconLog,0,0,FILE_END);
  124. STARTUPINFOA startupInfo;
  125. startupInfo.cb = sizeof(startupInfo);
  126. if (devconLog != INVALID_HANDLE_VALUE) {
  127. startupInfo.hStdOutput = devconLog;
  128. startupInfo.hStdError = devconLog;
  129. }
  130. PROCESS_INFORMATION processInfo;
  131. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  132. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  133. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" enable @" + deviceInstanceId).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  134. if (devconLog != INVALID_HANDLE_VALUE)
  135. CloseHandle(devconLog);
  136. return false;
  137. }
  138. WaitForSingleObject(processInfo.hProcess,INFINITE);
  139. CloseHandle(processInfo.hProcess);
  140. CloseHandle(processInfo.hThread);
  141. if (devconLog != INVALID_HANDLE_VALUE)
  142. CloseHandle(devconLog);
  143. return true;
  144. }
  145. static void _syncIpsWithRegistry(const std::set<InetAddress> &haveIps,const std::string netCfgInstanceId)
  146. {
  147. // Update registry to contain all non-link-local IPs for this interface
  148. std::string regMultiIps,regMultiNetmasks;
  149. for(std::set<InetAddress>::const_iterator i(haveIps.begin());i!=haveIps.end();++i) {
  150. if (!i->isLinkLocal()) {
  151. regMultiIps.append(i->toIpString());
  152. regMultiIps.push_back((char)0);
  153. regMultiNetmasks.append(i->netmask().toIpString());
  154. regMultiNetmasks.push_back((char)0);
  155. }
  156. }
  157. HKEY tcpIpInterfaces;
  158. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  159. if (regMultiIps.length()) {
  160. regMultiIps.push_back((char)0);
  161. regMultiNetmasks.push_back((char)0);
  162. RegSetKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"IPAddress",REG_MULTI_SZ,regMultiIps.data(),(DWORD)regMultiIps.length());
  163. RegSetKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"SubnetMask",REG_MULTI_SZ,regMultiNetmasks.data(),(DWORD)regMultiNetmasks.length());
  164. } else {
  165. RegDeleteKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"IPAddress");
  166. RegDeleteKeyValueA(tcpIpInterfaces,netCfgInstanceId.c_str(),"SubnetMask");
  167. }
  168. }
  169. RegCloseKey(tcpIpInterfaces);
  170. }
  171. WindowsEthernetTap::WindowsEthernetTap(
  172. const RuntimeEnvironment *renv,
  173. const char *tag,
  174. const MAC &mac,
  175. unsigned int mtu,
  176. void (*handler)(void *,const MAC &,const MAC &,unsigned int,const Buffer<4096> &),
  177. void *arg)
  178. throw(std::runtime_error) :
  179. EthernetTap("WindowsEthernetTap",mac,mtu),
  180. _r(renv),
  181. _handler(handler),
  182. _arg(arg),
  183. _tap(INVALID_HANDLE_VALUE),
  184. _injectSemaphore(INVALID_HANDLE_VALUE),
  185. _run(true),
  186. _initialized(false),
  187. _enabled(true)
  188. {
  189. char subkeyName[4096];
  190. char subkeyClass[4096];
  191. char data[4096];
  192. if (mtu > ZT_IF_MTU)
  193. throw std::runtime_error("MTU too large for Windows tap");
  194. Mutex::Lock _l(_systemTapInitLock);
  195. HKEY nwAdapters;
  196. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  197. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  198. std::set<std::string> existingDeviceInstances;
  199. std::string mySubkeyName;
  200. // Look for the tap instance that corresponds with our interface tag (network ID)
  201. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  202. DWORD type;
  203. DWORD dataLen;
  204. DWORD subkeyNameLen = sizeof(subkeyName);
  205. DWORD subkeyClassLen = sizeof(subkeyClass);
  206. FILETIME lastWriteTime;
  207. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  208. type = 0;
  209. dataLen = sizeof(data);
  210. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  211. data[dataLen] = '\0';
  212. if (!strnicmp(data,"zttap",5)) {
  213. std::string instanceId;
  214. type = 0;
  215. dataLen = sizeof(data);
  216. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  217. instanceId.assign(data,dataLen);
  218. existingDeviceInstances.insert(instanceId);
  219. }
  220. std::string instanceIdPath;
  221. type = 0;
  222. dataLen = sizeof(data);
  223. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  224. instanceIdPath.assign(data,dataLen);
  225. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  226. type = 0;
  227. dataLen = sizeof(data);
  228. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  229. data[dataLen] = '\0';
  230. if (!strcmp(data,tag)) {
  231. _netCfgInstanceId = instanceId;
  232. _deviceInstanceId = instanceIdPath;
  233. mySubkeyName = subkeyName;
  234. break; // found it!
  235. }
  236. }
  237. }
  238. }
  239. }
  240. } else break; // no more subkeys or error occurred enumerating them
  241. }
  242. // If there is no device, try to create one
  243. if (_netCfgInstanceId.length() == 0) {
  244. // Log devcon output to a file
  245. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  246. if (devconLog == INVALID_HANDLE_VALUE) {
  247. LOG("WARNING: unable to open devcon.log");
  248. } else {
  249. SetFilePointer(devconLog,0,0,FILE_END);
  250. }
  251. // Execute devcon to install an instance of the Microsoft Loopback Adapter
  252. STARTUPINFOA startupInfo;
  253. startupInfo.cb = sizeof(startupInfo);
  254. if (devconLog != INVALID_HANDLE_VALUE) {
  255. SetFilePointer(devconLog,0,0,FILE_END);
  256. startupInfo.hStdOutput = devconLog;
  257. startupInfo.hStdError = devconLog;
  258. }
  259. PROCESS_INFORMATION processInfo;
  260. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  261. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  262. if (!CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" install \"" + _r->homePath + _winEnv.tapDriver + "\" zttap200").c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  263. RegCloseKey(nwAdapters);
  264. if (devconLog != INVALID_HANDLE_VALUE)
  265. CloseHandle(devconLog);
  266. throw std::runtime_error(std::string("unable to find or execute devcon at ") + _winEnv.devcon);
  267. }
  268. WaitForSingleObject(processInfo.hProcess,INFINITE);
  269. CloseHandle(processInfo.hProcess);
  270. CloseHandle(processInfo.hThread);
  271. if (devconLog != INVALID_HANDLE_VALUE)
  272. CloseHandle(devconLog);
  273. // Scan for the new instance by simply looking for taps that weren't
  274. // there originally. The static mutex we lock ensures this can't step
  275. // on its own toes.
  276. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  277. DWORD type;
  278. DWORD dataLen;
  279. DWORD subkeyNameLen = sizeof(subkeyName);
  280. DWORD subkeyClassLen = sizeof(subkeyClass);
  281. FILETIME lastWriteTime;
  282. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  283. type = 0;
  284. dataLen = sizeof(data);
  285. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  286. data[dataLen] = '\0';
  287. if (!strnicmp(data,"zttap",5)) {
  288. type = 0;
  289. dataLen = sizeof(data);
  290. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  291. if (existingDeviceInstances.count(std::string(data,dataLen)) == 0) {
  292. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  293. _netCfgInstanceId.assign(data,dataLen);
  294. type = 0;
  295. dataLen = sizeof(data);
  296. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  297. _deviceInstanceId.assign(data,dataLen);
  298. mySubkeyName = subkeyName;
  299. // Disable DHCP by default on newly created devices
  300. HKEY tcpIpInterfaces;
  301. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  302. DWORD enable = 0;
  303. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  304. RegCloseKey(tcpIpInterfaces);
  305. }
  306. break; // found it!
  307. }
  308. }
  309. }
  310. }
  311. } else break; // no more keys or error occurred
  312. }
  313. }
  314. if (_netCfgInstanceId.length() > 0) {
  315. char tmps[4096];
  316. 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;
  317. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  318. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  319. DWORD tmp = mtu;
  320. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MTU",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  321. tmp = 0;
  322. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  323. RegCloseKey(nwAdapters);
  324. } else {
  325. RegCloseKey(nwAdapters);
  326. throw std::runtime_error("unable to find or create tap adapter");
  327. }
  328. // Convert device GUID junk... blech... is there an easier way to do this?
  329. {
  330. char nobraces[128];
  331. const char *nbtmp1 = _netCfgInstanceId.c_str();
  332. char *nbtmp2 = nobraces;
  333. while (*nbtmp1) {
  334. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  335. *nbtmp2++ = *nbtmp1;
  336. ++nbtmp1;
  337. }
  338. *nbtmp2 = (char)0;
  339. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  340. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  341. }
  342. // Start background thread that actually performs I/O
  343. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  344. _thread = Thread::start(this);
  345. // Certain functions can now work (e.g. ips())
  346. _initialized = true;
  347. }
  348. WindowsEthernetTap::~WindowsEthernetTap()
  349. {
  350. _run = false;
  351. ReleaseSemaphore(_injectSemaphore,1,NULL);
  352. Thread::join(_thread);
  353. CloseHandle(_injectSemaphore);
  354. _disableTapDevice(_r,_deviceInstanceId);
  355. }
  356. void WindowsEthernetTap::setEnabled(bool en)
  357. {
  358. _enabled = en;
  359. }
  360. bool WindowsEthernetTap::enabled() const
  361. {
  362. return _enabled;
  363. }
  364. void WindowsEthernetTap::setDisplayName(const char *dn)
  365. {
  366. if (!_initialized)
  367. return;
  368. HKEY ifp;
  369. 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) {
  370. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  371. RegCloseKey(ifp);
  372. }
  373. }
  374. bool WindowsEthernetTap::addIP(const InetAddress &ip)
  375. {
  376. if (!_initialized)
  377. return false;
  378. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  379. return false;
  380. std::set<InetAddress> haveIps(ips());
  381. try {
  382. // Add IP to interface at the netlink level if not already assigned.
  383. if (!haveIps.count(ip)) {
  384. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  385. MIB_UNICASTIPADDRESS_ROW ipr;
  386. InitializeUnicastIpAddressEntry(&ipr);
  387. if (ip.isV4()) {
  388. ipr.Address.Ipv4.sin_family = AF_INET;
  389. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)ip.rawIpData());
  390. ipr.OnLinkPrefixLength = ip.port();
  391. if (ipr.OnLinkPrefixLength >= 32)
  392. return false;
  393. } else if (ip.isV6()) {
  394. ipr.Address.Ipv6.sin6_family = AF_INET6;
  395. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,ip.rawIpData(),16);
  396. ipr.OnLinkPrefixLength = ip.port();
  397. if (ipr.OnLinkPrefixLength >= 128)
  398. return false;
  399. } else return false;
  400. ipr.PrefixOrigin = IpPrefixOriginManual;
  401. ipr.SuffixOrigin = IpSuffixOriginManual;
  402. ipr.ValidLifetime = 0xffffffff;
  403. ipr.PreferredLifetime = 0xffffffff;
  404. ipr.InterfaceLuid = ifidx.first;
  405. ipr.InterfaceIndex = ifidx.second;
  406. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  407. haveIps.insert(ip);
  408. } else {
  409. LOG("unable to add IP address %s to interface %s: %d",ip.toString().c_str(),deviceName().c_str(),(int)GetLastError());
  410. return false;
  411. }
  412. }
  413. _syncIpsWithRegistry(haveIps,_netCfgInstanceId);
  414. } catch (std::exception &exc) {
  415. LOG("unexpected exception adding IP address %s to %s: %s",ip.toString().c_str(),deviceName().c_str(),exc.what());
  416. return false;
  417. } catch ( ... ) {
  418. LOG("unexpected exception adding IP address %s to %s: unknown exception",ip.toString().c_str(),deviceName().c_str());
  419. return false;
  420. }
  421. return true;
  422. }
  423. bool WindowsEthernetTap::removeIP(const InetAddress &ip)
  424. {
  425. if (!_initialized)
  426. return false;
  427. try {
  428. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  429. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  430. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  431. for(DWORD i=0;i<ipt->NumEntries;++i) {
  432. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  433. InetAddress addr;
  434. switch(ipt->Table[i].Address.si_family) {
  435. case AF_INET:
  436. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  437. break;
  438. case AF_INET6:
  439. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  440. if (addr.isLinkLocal())
  441. continue; // can't remove link-local IPv6 addresses
  442. break;
  443. }
  444. if (addr == ip) {
  445. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  446. FreeMibTable(ipt);
  447. _syncIpsWithRegistry(ips(),_netCfgInstanceId);
  448. return true;
  449. }
  450. }
  451. }
  452. FreeMibTable((PVOID)ipt);
  453. }
  454. } catch (std::exception &exc) {
  455. LOG("unexpected exception removing IP address %s from %s: %s",ip.toString().c_str(),deviceName().c_str(),exc.what());
  456. } catch ( ... ) {
  457. LOG("unexpected exception removing IP address %s from %s: unknown exception",ip.toString().c_str(),deviceName().c_str());
  458. }
  459. return false;
  460. }
  461. std::set<InetAddress> WindowsEthernetTap::ips() const
  462. {
  463. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  464. std::set<InetAddress> addrs;
  465. if (!_initialized)
  466. return addrs;
  467. try {
  468. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  469. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  470. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  471. for(DWORD i=0;i<ipt->NumEntries;++i) {
  472. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  473. switch(ipt->Table[i].Address.si_family) {
  474. case AF_INET: {
  475. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  476. if (ip != InetAddress::LO4)
  477. addrs.insert(ip);
  478. } break;
  479. case AF_INET6: {
  480. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  481. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  482. addrs.insert(ip);
  483. } break;
  484. }
  485. }
  486. }
  487. FreeMibTable(ipt);
  488. }
  489. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  490. return addrs;
  491. }
  492. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  493. {
  494. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > (ZT_IF_MTU)))
  495. return;
  496. {
  497. Mutex::Lock _l(_injectPending_m);
  498. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  499. char *d = _injectPending.back().first.data;
  500. to.copyTo(d,6);
  501. from.copyTo(d + 6,6);
  502. d[12] = (char)((etherType >> 8) & 0xff);
  503. d[13] = (char)(etherType & 0xff);
  504. memcpy(d + 14,data,len);
  505. }
  506. ReleaseSemaphore(_injectSemaphore,1,NULL);
  507. }
  508. std::string WindowsEthernetTap::deviceName() const
  509. {
  510. return _netCfgInstanceId;
  511. }
  512. std::string WindowsEthernetTap::persistentId() const
  513. {
  514. return _deviceInstanceId;
  515. }
  516. bool WindowsEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  517. {
  518. if (!_initialized)
  519. return false;
  520. HANDLE t = _tap;
  521. if (t == INVALID_HANDLE_VALUE)
  522. return false;
  523. std::set<MulticastGroup> newGroups;
  524. // Ensure that groups are added for each IP... this handles the MAC:ADI
  525. // groups that are created from IPv4 addresses. Some of these may end
  526. // up being duplicates of what the IOCTL returns but that's okay since
  527. // the set<> will filter that.
  528. std::set<InetAddress> ipaddrs(ips());
  529. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  530. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  531. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  532. // level... something Windows does not seem to expose ordinarily. This lets
  533. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  534. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  535. DWORD bytesReturned = 0;
  536. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  537. MAC mac;
  538. DWORD i = 0;
  539. while ((i + 6) <= bytesReturned) {
  540. mac.setTo(mcastbuf + i,6);
  541. i += 6;
  542. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  543. // exclude the nulls that may be returned or any other junk Windows puts in there
  544. newGroups.insert(MulticastGroup(mac,0));
  545. }
  546. }
  547. }
  548. bool changed = false;
  549. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  550. if (!groups.count(*mg)) {
  551. groups.insert(*mg);
  552. changed = true;
  553. }
  554. }
  555. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  556. if ((!newGroups.count(*mg))&&(*mg != _blindWildcardMulticastGroup)) {
  557. groups.erase(mg++);
  558. changed = true;
  559. } else ++mg;
  560. }
  561. return changed;
  562. }
  563. void WindowsEthernetTap::threadMain()
  564. throw()
  565. {
  566. char tapPath[256];
  567. OVERLAPPED tapOvlRead,tapOvlWrite;
  568. HANDLE wait4[3];
  569. char *tapReadBuf = (char *)0;
  570. // Shouldn't be needed, but Windows does not overcommit. This Windows
  571. // tap code is defensive to schizoid paranoia degrees.
  572. while (!tapReadBuf) {
  573. tapReadBuf = (char *)::malloc(ZT_IF_MTU + 32);
  574. if (!tapReadBuf)
  575. Sleep(1000);
  576. }
  577. // Tap is in this weird Windows global pseudo file space
  578. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  579. // More insanity: repetatively try to enable/disable tap device. The first
  580. // time we succeed, close it and do it again. This is to fix a driver init
  581. // bug that seems to be extremely non-deterministic and to only occur after
  582. // headless MSI upgrade. It cannot be reproduced in any other circumstance.
  583. bool throwOneAway = true;
  584. while (_run) {
  585. _disableTapDevice(_r,_deviceInstanceId);
  586. Sleep(250);
  587. if (!_enableTapDevice(_r,_deviceInstanceId)) {
  588. ::free(tapReadBuf);
  589. _enabled = false;
  590. return; // only happens if devcon is missing or totally fails
  591. }
  592. Sleep(250);
  593. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  594. if (_tap == INVALID_HANDLE_VALUE) {
  595. Sleep(500);
  596. continue;
  597. }
  598. uint32_t tmpi = 1;
  599. DWORD bytesReturned = 0;
  600. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  601. if (throwOneAway) {
  602. throwOneAway = false;
  603. CloseHandle(_tap);
  604. _tap = INVALID_HANDLE_VALUE;
  605. Sleep(250);
  606. continue;
  607. } else break;
  608. }
  609. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  610. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  611. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  612. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  613. wait4[0] = _injectSemaphore;
  614. wait4[1] = tapOvlRead.hEvent;
  615. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  616. // Start overlapped read, which is always active
  617. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  618. bool writeInProgress = false;
  619. for(;;) {
  620. if (!_run) break;
  621. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,5000,TRUE);
  622. if (!_run) break;
  623. if ((r == WAIT_TIMEOUT)||(r == WAIT_FAILED))
  624. continue;
  625. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  626. DWORD bytesRead = 0;
  627. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  628. if ((bytesRead > 14)&&(_enabled)) {
  629. MAC to(tapReadBuf,6);
  630. MAC from(tapReadBuf + 6,6);
  631. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  632. try {
  633. Buffer<4096> tmp(tapReadBuf + 14,bytesRead - 14);
  634. _handler(_arg,from,to,etherType,tmp);
  635. } catch ( ... ) {} // handlers should not throw
  636. }
  637. }
  638. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  639. }
  640. if (writeInProgress) {
  641. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  642. writeInProgress = false;
  643. _injectPending_m.lock();
  644. _injectPending.pop();
  645. } else continue; // still writing, so skip code below and wait
  646. } else _injectPending_m.lock();
  647. if (!_injectPending.empty()) {
  648. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  649. writeInProgress = true;
  650. }
  651. _injectPending_m.unlock();
  652. }
  653. CancelIo(_tap);
  654. CloseHandle(tapOvlRead.hEvent);
  655. CloseHandle(tapOvlWrite.hEvent);
  656. CloseHandle(_tap);
  657. _tap = INVALID_HANDLE_VALUE;
  658. ::free(tapReadBuf);
  659. }
  660. bool WindowsEthernetTap::deletePersistentTapDevice(const RuntimeEnvironment *_r,const char *pid)
  661. {
  662. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  663. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  664. STARTUPINFOA startupInfo;
  665. startupInfo.cb = sizeof(startupInfo);
  666. if (devconLog != INVALID_HANDLE_VALUE) {
  667. SetFilePointer(devconLog,0,0,FILE_END);
  668. startupInfo.hStdOutput = devconLog;
  669. startupInfo.hStdError = devconLog;
  670. }
  671. PROCESS_INFORMATION processInfo;
  672. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  673. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  674. if (CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" remove @" + pid).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  675. WaitForSingleObject(processInfo.hProcess,INFINITE);
  676. CloseHandle(processInfo.hProcess);
  677. CloseHandle(processInfo.hThread);
  678. if (devconLog != INVALID_HANDLE_VALUE)
  679. CloseHandle(devconLog);
  680. return true;
  681. }
  682. if (devconLog != INVALID_HANDLE_VALUE)
  683. CloseHandle(devconLog);
  684. return false;
  685. }
  686. int WindowsEthernetTap::cleanPersistentTapDevices(const RuntimeEnvironment *_r,const std::set<std::string> &exceptThese,bool alsoRemoveUnassociatedDevices)
  687. {
  688. char subkeyName[4096];
  689. char subkeyClass[4096];
  690. char data[4096];
  691. std::set<std::string> instanceIdPathsToRemove;
  692. {
  693. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  694. HKEY nwAdapters;
  695. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  696. return -1;
  697. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  698. DWORD type;
  699. DWORD dataLen;
  700. DWORD subkeyNameLen = sizeof(subkeyName);
  701. DWORD subkeyClassLen = sizeof(subkeyClass);
  702. FILETIME lastWriteTime;
  703. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  704. type = 0;
  705. dataLen = sizeof(data);
  706. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  707. data[dataLen] = '\0';
  708. if (!strnicmp(data,"zttap",5)) {
  709. std::string instanceIdPath;
  710. type = 0;
  711. dataLen = sizeof(data);
  712. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  713. instanceIdPath.assign(data,dataLen);
  714. if (instanceIdPath.length() != 0) {
  715. type = 0;
  716. dataLen = sizeof(data);
  717. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  718. if (dataLen <= 0) {
  719. if (alsoRemoveUnassociatedDevices)
  720. instanceIdPathsToRemove.insert(instanceIdPath);
  721. } else {
  722. if (!exceptThese.count(std::string(data,dataLen)))
  723. instanceIdPathsToRemove.insert(instanceIdPath);
  724. }
  725. } else if (alsoRemoveUnassociatedDevices)
  726. instanceIdPathsToRemove.insert(instanceIdPath);
  727. }
  728. }
  729. }
  730. } else break; // end of list or failure
  731. }
  732. RegCloseKey(nwAdapters);
  733. }
  734. int removed = 0;
  735. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  736. if (deletePersistentTapDevice(_r,iidp->c_str()))
  737. ++removed;
  738. }
  739. return removed;
  740. }
  741. } // namespace ZeroTier