WindowsEthernetTap.cpp 29 KB

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