WindowsEthernetTap.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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 manipulate devices one at a time to avoid weird driver layer demons
  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); // only one thread may mess with taps at a time, process-wide
  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.data[0],(unsigned int)mac.data[1],(unsigned int)mac.data[2],(unsigned int)mac.data[3],(unsigned int)mac.data[4],(unsigned int)mac.data[5]) + 1;
  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. } else {
  326. RegCloseKey(nwAdapters);
  327. throw std::runtime_error("unable to find or create tap adapter");
  328. }
  329. RegCloseKey(nwAdapters);
  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. } 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. } else return false;
  398. ipr.PrefixOrigin = IpPrefixOriginManual;
  399. ipr.SuffixOrigin = IpSuffixOriginManual;
  400. ipr.ValidLifetime = 0xffffffff;
  401. ipr.PreferredLifetime = 0xffffffff;
  402. ipr.InterfaceLuid = ifidx.first;
  403. ipr.InterfaceIndex = ifidx.second;
  404. if (CreateUnicastIpAddressEntry(&ipr) == NO_ERROR) {
  405. haveIps.insert(ip);
  406. } else {
  407. LOG("unable to add IP address %s to interface %s: %d",ip.toString().c_str(),deviceName().c_str(),(int)GetLastError());
  408. return false;
  409. }
  410. }
  411. _syncIpsWithRegistry(haveIps,_netCfgInstanceId);
  412. } catch (std::exception &exc) {
  413. LOG("unexpected exception adding IP address %s to %s: %s",ip.toString().c_str(),deviceName().c_str(),exc.what());
  414. } catch ( ... ) {
  415. LOG("unexpected exception adding IP address %s to %s: unknown exception",ip.toString().c_str(),deviceName().c_str());
  416. }
  417. return false;
  418. }
  419. bool WindowsEthernetTap::removeIP(const InetAddress &ip)
  420. {
  421. if (!_initialized)
  422. return false;
  423. try {
  424. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  425. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  426. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  427. for(DWORD i=0;i<ipt->NumEntries;++i) {
  428. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  429. InetAddress addr;
  430. switch(ipt->Table[i].Address.si_family) {
  431. case AF_INET:
  432. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  433. break;
  434. case AF_INET6:
  435. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  436. if (addr.isLinkLocal())
  437. continue; // can't remove link-local IPv6 addresses
  438. break;
  439. }
  440. if (addr == ip) {
  441. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  442. FreeMibTable(ipt);
  443. _syncIpsWithRegistry(ips(),_netCfgInstanceId);
  444. return true;
  445. }
  446. }
  447. }
  448. FreeMibTable((PVOID)ipt);
  449. }
  450. } catch (std::exception &exc) {
  451. LOG("unexpected exception removing IP address %s from %s: %s",ip.toString().c_str(),deviceName().c_str(),exc.what());
  452. } catch ( ... ) {
  453. LOG("unexpected exception removing IP address %s from %s: unknown exception",ip.toString().c_str(),deviceName().c_str());
  454. }
  455. return false;
  456. }
  457. std::set<InetAddress> WindowsEthernetTap::ips() const
  458. {
  459. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  460. std::set<InetAddress> addrs;
  461. if (!_initialized)
  462. return addrs;
  463. try {
  464. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  465. std::pair<NET_LUID,NET_IFINDEX> ifidx = _findAdapterByGuid(_deviceGuid);
  466. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  467. for(DWORD i=0;i<ipt->NumEntries;++i) {
  468. if ((ipt->Table[i].InterfaceLuid.Value == ifidx.first.Value)&&(ipt->Table[i].InterfaceIndex == ifidx.second)) {
  469. switch(ipt->Table[i].Address.si_family) {
  470. case AF_INET: {
  471. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  472. if (ip != InetAddress::LO4)
  473. addrs.insert(ip);
  474. } break;
  475. case AF_INET6: {
  476. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  477. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  478. addrs.insert(ip);
  479. } break;
  480. }
  481. }
  482. }
  483. FreeMibTable(ipt);
  484. }
  485. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  486. return addrs;
  487. }
  488. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  489. {
  490. if ((!_initialized)||(!_enabled))
  491. return;
  492. if (len > (ZT_IF_MTU))
  493. return; // sanity check
  494. {
  495. Mutex::Lock _l(_injectPending_m);
  496. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  497. char *d = _injectPending.back().first.data;
  498. memcpy(d,to.data,6);
  499. memcpy(d + 6,from.data,6);
  500. d[12] = (char)((etherType >> 8) & 0xff);
  501. d[13] = (char)(etherType & 0xff);
  502. memcpy(d + 14,data,len);
  503. }
  504. ReleaseSemaphore(_injectSemaphore,1,NULL);
  505. }
  506. std::string WindowsEthernetTap::deviceName() const
  507. {
  508. return _netCfgInstanceId;
  509. }
  510. std::string WindowsEthernetTap::persistentId() const
  511. {
  512. return _deviceInstanceId;
  513. }
  514. bool WindowsEthernetTap::updateMulticastGroups(std::set<MulticastGroup> &groups)
  515. {
  516. if (!_initialized)
  517. return false;
  518. HANDLE t = _tap;
  519. if (t == INVALID_HANDLE_VALUE)
  520. return false;
  521. std::set<MulticastGroup> newGroups;
  522. // Ensure that groups are added for each IP... this handles the MAC:ADI
  523. // groups that are created from IPv4 addresses. Some of these may end
  524. // up being duplicates of what the IOCTL returns but that's okay since
  525. // the set<> will filter that.
  526. std::set<InetAddress> ipaddrs(ips());
  527. for(std::set<InetAddress>::const_iterator i(ipaddrs.begin());i!=ipaddrs.end();++i)
  528. newGroups.insert(MulticastGroup::deriveMulticastGroupForAddressResolution(*i));
  529. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  530. // level... something Windows does not seem to expose ordinarily. This lets
  531. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  532. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  533. DWORD bytesReturned = 0;
  534. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  535. MAC mac;
  536. DWORD i = 0;
  537. while ((i + 6) <= bytesReturned) {
  538. mac.data[0] = mcastbuf[i++];
  539. mac.data[1] = mcastbuf[i++];
  540. mac.data[2] = mcastbuf[i++];
  541. mac.data[3] = mcastbuf[i++];
  542. mac.data[4] = mcastbuf[i++];
  543. mac.data[5] = mcastbuf[i++];
  544. if (mac.isMulticast()) {
  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. newGroups.insert(_blindWildcardMulticastGroup); // always join this
  551. bool changed = false;
  552. for(std::set<MulticastGroup>::iterator mg(newGroups.begin());mg!=newGroups.end();++mg) {
  553. if (!groups.count(*mg)) {
  554. groups.insert(*mg);
  555. changed = true;
  556. }
  557. }
  558. for(std::set<MulticastGroup>::iterator mg(groups.begin());mg!=groups.end();) {
  559. if (!newGroups.count(*mg)) {
  560. groups.erase(mg++);
  561. changed = true;
  562. } else ++mg;
  563. }
  564. return changed;
  565. }
  566. void WindowsEthernetTap::threadMain()
  567. throw()
  568. {
  569. char tapPath[256];
  570. OVERLAPPED tapOvlRead,tapOvlWrite;
  571. HANDLE wait4[3];
  572. char *tapReadBuf = (char *)0;
  573. // Shouldn't be needed, but Windows does not overcommit. This Windows
  574. // tap code is defensive to schizoid paranoia degrees.
  575. while (!tapReadBuf) {
  576. tapReadBuf = (char *)::malloc(ZT_IF_MTU + 32);
  577. if (!tapReadBuf)
  578. Sleep(1000);
  579. }
  580. // Tap is in this weird Windows global pseudo file space
  581. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  582. // More insanity: repetatively try to enable/disable tap device. The first
  583. // time we succeed, close it and do it again. This is to fix a driver init
  584. // bug that seems to be extremely non-deterministic and to only occur after
  585. // headless MSI upgrade. It cannot be reproduced in any other circumstance.
  586. bool throwOneAway = true;
  587. while (_run) {
  588. _disableTapDevice(_r,_deviceInstanceId);
  589. Sleep(250);
  590. if (!_enableTapDevice(_r,_deviceInstanceId)) {
  591. ::free(tapReadBuf);
  592. _enabled = false;
  593. return; // only happens if devcon is missing or totally fails
  594. }
  595. Sleep(250);
  596. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  597. if (_tap == INVALID_HANDLE_VALUE) {
  598. Sleep(500);
  599. continue;
  600. }
  601. uint32_t tmpi = 1;
  602. DWORD bytesReturned = 0;
  603. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  604. if (throwOneAway) {
  605. throwOneAway = false;
  606. CloseHandle(_tap);
  607. _tap = INVALID_HANDLE_VALUE;
  608. Sleep(250);
  609. continue;
  610. } else break;
  611. }
  612. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  613. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  614. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  615. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  616. wait4[0] = _injectSemaphore;
  617. wait4[1] = tapOvlRead.hEvent;
  618. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  619. // Start overlapped read, which is always active
  620. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  621. bool writeInProgress = false;
  622. for(;;) {
  623. if (!_run) break;
  624. DWORD r = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,5000,TRUE);
  625. if (!_run) break;
  626. if ((r == WAIT_TIMEOUT)||(r == WAIT_FAILED))
  627. continue;
  628. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  629. DWORD bytesRead = 0;
  630. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  631. if ((bytesRead > 14)&&(_enabled)) {
  632. MAC to(tapReadBuf);
  633. MAC from(tapReadBuf + 6);
  634. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  635. try {
  636. Buffer<4096> tmp(tapReadBuf + 14,bytesRead - 14);
  637. _handler(_arg,from,to,etherType,tmp);
  638. } catch ( ... ) {} // handlers should not throw
  639. }
  640. }
  641. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  642. }
  643. if (writeInProgress) {
  644. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  645. writeInProgress = false;
  646. _injectPending_m.lock();
  647. _injectPending.pop();
  648. } else continue; // still writing, so skip code below and wait
  649. } else _injectPending_m.lock();
  650. if (!_injectPending.empty()) {
  651. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  652. writeInProgress = true;
  653. }
  654. _injectPending_m.unlock();
  655. }
  656. CancelIo(_tap);
  657. CloseHandle(tapOvlRead.hEvent);
  658. CloseHandle(tapOvlWrite.hEvent);
  659. CloseHandle(_tap);
  660. _tap = INVALID_HANDLE_VALUE;
  661. ::free(tapReadBuf);
  662. }
  663. bool WindowsEthernetTap::deletePersistentTapDevice(const RuntimeEnvironment *_r,const char *pid)
  664. {
  665. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  666. HANDLE devconLog = CreateFileA((_r->homePath + "\\devcon.log").c_str(),GENERIC_WRITE,FILE_SHARE_READ|FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
  667. STARTUPINFOA startupInfo;
  668. startupInfo.cb = sizeof(startupInfo);
  669. if (devconLog != INVALID_HANDLE_VALUE) {
  670. SetFilePointer(devconLog,0,0,FILE_END);
  671. startupInfo.hStdOutput = devconLog;
  672. startupInfo.hStdError = devconLog;
  673. }
  674. PROCESS_INFORMATION processInfo;
  675. memset(&startupInfo,0,sizeof(STARTUPINFOA));
  676. memset(&processInfo,0,sizeof(PROCESS_INFORMATION));
  677. if (CreateProcessA(NULL,(LPSTR)(std::string("\"") + _r->homePath + _winEnv.devcon + "\" remove @" + pid).c_str(),NULL,NULL,FALSE,0,NULL,NULL,&startupInfo,&processInfo)) {
  678. WaitForSingleObject(processInfo.hProcess,INFINITE);
  679. CloseHandle(processInfo.hProcess);
  680. CloseHandle(processInfo.hThread);
  681. if (devconLog != INVALID_HANDLE_VALUE)
  682. CloseHandle(devconLog);
  683. return true;
  684. }
  685. if (devconLog != INVALID_HANDLE_VALUE)
  686. CloseHandle(devconLog);
  687. return false;
  688. }
  689. int WindowsEthernetTap::cleanPersistentTapDevices(const RuntimeEnvironment *_r,const std::set<std::string> &exceptThese,bool alsoRemoveUnassociatedDevices)
  690. {
  691. char subkeyName[4096];
  692. char subkeyClass[4096];
  693. char data[4096];
  694. std::set<std::string> instanceIdPathsToRemove;
  695. {
  696. Mutex::Lock _l(_systemTapInitLock); // only one thread may mess with taps at a time, process-wide
  697. HKEY nwAdapters;
  698. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  699. return -1;
  700. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  701. DWORD type;
  702. DWORD dataLen;
  703. DWORD subkeyNameLen = sizeof(subkeyName);
  704. DWORD subkeyClassLen = sizeof(subkeyClass);
  705. FILETIME lastWriteTime;
  706. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  707. type = 0;
  708. dataLen = sizeof(data);
  709. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  710. data[dataLen] = '\0';
  711. if (!strnicmp(data,"zttap",5)) {
  712. std::string instanceIdPath;
  713. type = 0;
  714. dataLen = sizeof(data);
  715. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  716. instanceIdPath.assign(data,dataLen);
  717. if (instanceIdPath.length() != 0) {
  718. type = 0;
  719. dataLen = sizeof(data);
  720. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  721. if (dataLen <= 0) {
  722. if (alsoRemoveUnassociatedDevices)
  723. instanceIdPathsToRemove.insert(instanceIdPath);
  724. } else {
  725. if (!exceptThese.count(std::string(data,dataLen)))
  726. instanceIdPathsToRemove.insert(instanceIdPath);
  727. }
  728. } else if (alsoRemoveUnassociatedDevices)
  729. instanceIdPathsToRemove.insert(instanceIdPath);
  730. }
  731. }
  732. }
  733. } else break; // end of list or failure
  734. }
  735. RegCloseKey(nwAdapters);
  736. }
  737. int removed = 0;
  738. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  739. if (deletePersistentTapDevice(_r,iidp->c_str()))
  740. ++removed;
  741. }
  742. return removed;
  743. }
  744. } // namespace ZeroTier