WindowsEthernetTap.cpp 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2016 ZeroTier, Inc. https://www.zerotier.com/
  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. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <stdint.h>
  21. #include <string.h>
  22. #include <WinSock2.h>
  23. #include <Windows.h>
  24. #include <tchar.h>
  25. #include <malloc.h>
  26. #include <winreg.h>
  27. #include <wchar.h>
  28. #include <ws2ipdef.h>
  29. #include <WS2tcpip.h>
  30. #include <IPHlpApi.h>
  31. #include <nldef.h>
  32. #include <netioapi.h>
  33. #include <atlbase.h>
  34. #include <netlistmgr.h>
  35. #include <nldef.h>
  36. #include <SetupAPI.h>
  37. #include <newdev.h>
  38. #include <cfgmgr32.h>
  39. #include <iostream>
  40. #include <set>
  41. #include "../node/Constants.hpp"
  42. #include "../node/Utils.hpp"
  43. #include "../node/Mutex.hpp"
  44. #include "WindowsEthernetTap.hpp"
  45. #include "OSUtils.hpp"
  46. #include "..\windows\TapDriver6\tap-windows.h"
  47. // Create a fake unused default route to force detection of network type on networks without gateways
  48. #define ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  49. // Function signatures of dynamically loaded functions, from newdev.h, setupapi.h, and cfgmgr32.h
  50. typedef BOOL (WINAPI *UpdateDriverForPlugAndPlayDevicesA_t)(_In_opt_ HWND hwndParent,_In_ LPCSTR HardwareId,_In_ LPCSTR FullInfPath,_In_ DWORD InstallFlags,_Out_opt_ PBOOL bRebootRequired);
  51. typedef BOOL (WINAPI *SetupDiGetINFClassA_t)(_In_ PCSTR InfName,_Out_ LPGUID ClassGuid,_Out_writes_(ClassNameSize) PSTR ClassName,_In_ DWORD ClassNameSize,_Out_opt_ PDWORD RequiredSize);
  52. typedef HDEVINFO (WINAPI *SetupDiCreateDeviceInfoList_t)(_In_opt_ CONST GUID *ClassGuid,_In_opt_ HWND hwndParent);
  53. typedef BOOL (WINAPI *SetupDiCreateDeviceInfoA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PCSTR DeviceName,_In_ CONST GUID *ClassGuid,_In_opt_ PCSTR DeviceDescription,_In_opt_ HWND hwndParent,_In_ DWORD CreationFlags,_Out_opt_ PSP_DEVINFO_DATA DeviceInfoData);
  54. typedef BOOL (WINAPI *SetupDiSetDeviceRegistryPropertyA_t)(_In_ HDEVINFO DeviceInfoSet,_Inout_ PSP_DEVINFO_DATA DeviceInfoData,_In_ DWORD Property,_In_reads_bytes_opt_(PropertyBufferSize) CONST BYTE *PropertyBuffer,_In_ DWORD PropertyBufferSize);
  55. typedef BOOL (WINAPI *SetupDiCallClassInstaller_t)(_In_ DI_FUNCTION InstallFunction,_In_ HDEVINFO DeviceInfoSet,_In_opt_ PSP_DEVINFO_DATA DeviceInfoData);
  56. typedef BOOL (WINAPI *SetupDiDestroyDeviceInfoList_t)(_In_ HDEVINFO DeviceInfoSet);
  57. typedef HDEVINFO (WINAPI *SetupDiGetClassDevsExA_t)(_In_opt_ CONST GUID *ClassGuid,_In_opt_ PCSTR Enumerator,_In_opt_ HWND hwndParent,_In_ DWORD Flags,_In_opt_ HDEVINFO DeviceInfoSet,_In_opt_ PCSTR MachineName,_Reserved_ PVOID Reserved);
  58. typedef BOOL (WINAPI *SetupDiOpenDeviceInfoA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PCSTR DeviceInstanceId,_In_opt_ HWND hwndParent,_In_ DWORD OpenFlags,_Out_opt_ PSP_DEVINFO_DATA DeviceInfoData);
  59. typedef BOOL (WINAPI *SetupDiEnumDeviceInfo_t)(_In_ HDEVINFO DeviceInfoSet,_In_ DWORD MemberIndex,_Out_ PSP_DEVINFO_DATA DeviceInfoData);
  60. typedef BOOL (WINAPI *SetupDiSetClassInstallParamsA_t)(_In_ HDEVINFO DeviceInfoSet,_In_opt_ PSP_DEVINFO_DATA DeviceInfoData,_In_reads_bytes_opt_(ClassInstallParamsSize) PSP_CLASSINSTALL_HEADER ClassInstallParams,_In_ DWORD ClassInstallParamsSize);
  61. typedef CONFIGRET (WINAPI *CM_Get_Device_ID_ExA_t)(_In_ DEVINST dnDevInst,_Out_writes_(BufferLen) PSTR Buffer,_In_ ULONG BufferLen,_In_ ULONG ulFlags,_In_opt_ HMACHINE hMachine);
  62. typedef BOOL (WINAPI *SetupDiGetDeviceInstanceIdA_t)(_In_ HDEVINFO DeviceInfoSet,_In_ PSP_DEVINFO_DATA DeviceInfoData,_Out_writes_opt_(DeviceInstanceIdSize) PSTR DeviceInstanceId,_In_ DWORD DeviceInstanceIdSize,_Out_opt_ PDWORD RequiredSize);
  63. namespace ZeroTier {
  64. namespace {
  65. // Static/singleton class that when initialized loads a bunch of environment information and a few dynamically loaded DLLs
  66. class WindowsEthernetTapEnv
  67. {
  68. public:
  69. WindowsEthernetTapEnv()
  70. {
  71. #ifdef _WIN64
  72. is64Bit = TRUE;
  73. tapDriverPath = "\\tap-windows\\x64\\zttap300.inf";
  74. #else
  75. is64Bit = FALSE;
  76. IsWow64Process(GetCurrentProcess(),&is64Bit);
  77. if (is64Bit) {
  78. fprintf(stderr,"FATAL: you must use the 64-bit ZeroTier One service on 64-bit Windows systems\r\n");
  79. _exit(1);
  80. }
  81. tapDriverPath = "\\tap-windows\\x86\\zttap300.inf";
  82. #endif
  83. tapDriverName = "zttap300";
  84. setupApiMod = LoadLibraryA("setupapi.dll");
  85. if (!setupApiMod) {
  86. fprintf(stderr,"FATAL: unable to dynamically load setupapi.dll\r\n");
  87. _exit(1);
  88. }
  89. if (!(this->SetupDiGetINFClassA = (SetupDiGetINFClassA_t)GetProcAddress(setupApiMod,"SetupDiGetINFClassA"))) {
  90. fprintf(stderr,"FATAL: SetupDiGetINFClassA not found in setupapi.dll\r\n");
  91. _exit(1);
  92. }
  93. if (!(this->SetupDiCreateDeviceInfoList = (SetupDiCreateDeviceInfoList_t)GetProcAddress(setupApiMod,"SetupDiCreateDeviceInfoList"))) {
  94. fprintf(stderr,"FATAL: SetupDiCreateDeviceInfoList not found in setupapi.dll\r\n");
  95. _exit(1);
  96. }
  97. if (!(this->SetupDiCreateDeviceInfoA = (SetupDiCreateDeviceInfoA_t)GetProcAddress(setupApiMod,"SetupDiCreateDeviceInfoA"))) {
  98. fprintf(stderr,"FATAL: SetupDiCreateDeviceInfoA not found in setupapi.dll\r\n");
  99. _exit(1);
  100. }
  101. if (!(this->SetupDiSetDeviceRegistryPropertyA = (SetupDiSetDeviceRegistryPropertyA_t)GetProcAddress(setupApiMod,"SetupDiSetDeviceRegistryPropertyA"))) {
  102. fprintf(stderr,"FATAL: SetupDiSetDeviceRegistryPropertyA not found in setupapi.dll\r\n");
  103. _exit(1);
  104. }
  105. if (!(this->SetupDiCallClassInstaller = (SetupDiCallClassInstaller_t)GetProcAddress(setupApiMod,"SetupDiCallClassInstaller"))) {
  106. fprintf(stderr,"FATAL: SetupDiCallClassInstaller not found in setupapi.dll\r\n");
  107. _exit(1);
  108. }
  109. if (!(this->SetupDiDestroyDeviceInfoList = (SetupDiDestroyDeviceInfoList_t)GetProcAddress(setupApiMod,"SetupDiDestroyDeviceInfoList"))) {
  110. fprintf(stderr,"FATAL: SetupDiDestroyDeviceInfoList not found in setupapi.dll\r\n");
  111. _exit(1);
  112. }
  113. if (!(this->SetupDiGetClassDevsExA = (SetupDiGetClassDevsExA_t)GetProcAddress(setupApiMod,"SetupDiGetClassDevsExA"))) {
  114. fprintf(stderr,"FATAL: SetupDiGetClassDevsExA not found in setupapi.dll\r\n");
  115. _exit(1);
  116. }
  117. if (!(this->SetupDiOpenDeviceInfoA = (SetupDiOpenDeviceInfoA_t)GetProcAddress(setupApiMod,"SetupDiOpenDeviceInfoA"))) {
  118. fprintf(stderr,"FATAL: SetupDiOpenDeviceInfoA not found in setupapi.dll\r\n");
  119. _exit(1);
  120. }
  121. if (!(this->SetupDiEnumDeviceInfo = (SetupDiEnumDeviceInfo_t)GetProcAddress(setupApiMod,"SetupDiEnumDeviceInfo"))) {
  122. fprintf(stderr,"FATAL: SetupDiEnumDeviceInfo not found in setupapi.dll\r\n");
  123. _exit(1);
  124. }
  125. if (!(this->SetupDiSetClassInstallParamsA = (SetupDiSetClassInstallParamsA_t)GetProcAddress(setupApiMod,"SetupDiSetClassInstallParamsA"))) {
  126. fprintf(stderr,"FATAL: SetupDiSetClassInstallParamsA not found in setupapi.dll\r\n");
  127. _exit(1);
  128. }
  129. if (!(this->SetupDiGetDeviceInstanceIdA = (SetupDiGetDeviceInstanceIdA_t)GetProcAddress(setupApiMod,"SetupDiGetDeviceInstanceIdA"))) {
  130. fprintf(stderr,"FATAL: SetupDiGetDeviceInstanceIdA not found in setupapi.dll\r\n");
  131. _exit(1);
  132. }
  133. newDevMod = LoadLibraryA("newdev.dll");
  134. if (!newDevMod) {
  135. fprintf(stderr,"FATAL: unable to dynamically load newdev.dll\r\n");
  136. _exit(1);
  137. }
  138. if (!(this->UpdateDriverForPlugAndPlayDevicesA = (UpdateDriverForPlugAndPlayDevicesA_t)GetProcAddress(newDevMod,"UpdateDriverForPlugAndPlayDevicesA"))) {
  139. fprintf(stderr,"FATAL: UpdateDriverForPlugAndPlayDevicesA not found in newdev.dll\r\n");
  140. _exit(1);
  141. }
  142. cfgMgrMod = LoadLibraryA("cfgmgr32.dll");
  143. if (!cfgMgrMod) {
  144. fprintf(stderr,"FATAL: unable to dynamically load cfgmgr32.dll\r\n");
  145. _exit(1);
  146. }
  147. if (!(this->CM_Get_Device_ID_ExA = (CM_Get_Device_ID_ExA_t)GetProcAddress(cfgMgrMod,"CM_Get_Device_ID_ExA"))) {
  148. fprintf(stderr,"FATAL: CM_Get_Device_ID_ExA not found in cfgmgr32.dll\r\n");
  149. _exit(1);
  150. }
  151. }
  152. BOOL is64Bit; // is the system 64-bit, regardless of whether this binary is or not
  153. std::string tapDriverPath;
  154. std::string tapDriverName;
  155. UpdateDriverForPlugAndPlayDevicesA_t UpdateDriverForPlugAndPlayDevicesA;
  156. SetupDiGetINFClassA_t SetupDiGetINFClassA;
  157. SetupDiCreateDeviceInfoList_t SetupDiCreateDeviceInfoList;
  158. SetupDiCreateDeviceInfoA_t SetupDiCreateDeviceInfoA;
  159. SetupDiSetDeviceRegistryPropertyA_t SetupDiSetDeviceRegistryPropertyA;
  160. SetupDiCallClassInstaller_t SetupDiCallClassInstaller;
  161. SetupDiDestroyDeviceInfoList_t SetupDiDestroyDeviceInfoList;
  162. SetupDiGetClassDevsExA_t SetupDiGetClassDevsExA;
  163. SetupDiOpenDeviceInfoA_t SetupDiOpenDeviceInfoA;
  164. SetupDiEnumDeviceInfo_t SetupDiEnumDeviceInfo;
  165. SetupDiSetClassInstallParamsA_t SetupDiSetClassInstallParamsA;
  166. SetupDiGetDeviceInstanceIdA_t SetupDiGetDeviceInstanceIdA;
  167. CM_Get_Device_ID_ExA_t CM_Get_Device_ID_ExA;
  168. private:
  169. HMODULE setupApiMod;
  170. HMODULE newDevMod;
  171. HMODULE cfgMgrMod;
  172. };
  173. static const WindowsEthernetTapEnv WINENV;
  174. // Only create or delete devices one at a time
  175. static Mutex _systemTapInitLock;
  176. // Only perform installation or uninstallation options one at a time
  177. static Mutex _systemDeviceManagementLock;
  178. } // anonymous namespace
  179. std::string WindowsEthernetTap::addNewPersistentTapDevice(const char *pathToInf,std::string &deviceInstanceId)
  180. {
  181. Mutex::Lock _l(_systemDeviceManagementLock);
  182. GUID classGuid;
  183. char className[1024];
  184. if (!WINENV.SetupDiGetINFClassA(pathToInf,&classGuid,className,sizeof(className),(PDWORD)0)) {
  185. return std::string("SetupDiGetINFClassA() failed -- unable to read zttap driver INF file");
  186. }
  187. HDEVINFO deviceInfoSet = WINENV.SetupDiCreateDeviceInfoList(&classGuid,(HWND)0);
  188. if (deviceInfoSet == INVALID_HANDLE_VALUE) {
  189. return std::string("SetupDiCreateDeviceInfoList() failed");
  190. }
  191. SP_DEVINFO_DATA deviceInfoData;
  192. memset(&deviceInfoData,0,sizeof(deviceInfoData));
  193. deviceInfoData.cbSize = sizeof(deviceInfoData);
  194. if (!WINENV.SetupDiCreateDeviceInfoA(deviceInfoSet,className,&classGuid,(PCSTR)0,(HWND)0,DICD_GENERATE_ID,&deviceInfoData)) {
  195. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  196. return std::string("SetupDiCreateDeviceInfoA() failed");
  197. }
  198. if (!WINENV.SetupDiSetDeviceRegistryPropertyA(deviceInfoSet,&deviceInfoData,SPDRP_HARDWAREID,(const BYTE *)WINENV.tapDriverName.c_str(),(DWORD)(WINENV.tapDriverName.length() + 1))) {
  199. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  200. return std::string("SetupDiSetDeviceRegistryPropertyA() failed");
  201. }
  202. if (!WINENV.SetupDiCallClassInstaller(DIF_REGISTERDEVICE,deviceInfoSet,&deviceInfoData)) {
  203. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  204. return std::string("SetupDiCallClassInstaller(DIF_REGISTERDEVICE) failed");
  205. }
  206. // HACK: During upgrades, this can fail while the installer is still running. So make 60 attempts
  207. // with a 1s delay between each attempt.
  208. bool driverInstalled = false;
  209. for(int retryCounter=0;retryCounter<60;++retryCounter) {
  210. BOOL rebootRequired = FALSE;
  211. if (WINENV.UpdateDriverForPlugAndPlayDevicesA((HWND)0,WINENV.tapDriverName.c_str(),pathToInf,INSTALLFLAG_FORCE|INSTALLFLAG_NONINTERACTIVE,&rebootRequired)) {
  212. driverInstalled = true;
  213. break;
  214. } else Sleep(1000);
  215. }
  216. if (!driverInstalled) {
  217. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  218. return std::string("UpdateDriverForPlugAndPlayDevices() failed (made 60 attempts)");
  219. }
  220. char iidbuf[1024];
  221. DWORD iidReqSize = sizeof(iidbuf);
  222. if (WINENV.SetupDiGetDeviceInstanceIdA(deviceInfoSet,&deviceInfoData,iidbuf,sizeof(iidbuf),&iidReqSize)) {
  223. deviceInstanceId = iidbuf;
  224. } // failure here is not fatal since we only need this on Vista and 2008 -- other versions fill it into the registry automatically
  225. WINENV.SetupDiDestroyDeviceInfoList(deviceInfoSet);
  226. return std::string();
  227. }
  228. std::string WindowsEthernetTap::destroyAllLegacyPersistentTapDevices()
  229. {
  230. char subkeyName[1024];
  231. char subkeyClass[1024];
  232. char data[1024];
  233. std::set<std::string> instanceIdPathsToRemove;
  234. {
  235. HKEY nwAdapters;
  236. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  237. return std::string("Could not open registry key");
  238. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  239. DWORD type;
  240. DWORD dataLen;
  241. DWORD subkeyNameLen = sizeof(subkeyName);
  242. DWORD subkeyClassLen = sizeof(subkeyClass);
  243. FILETIME lastWriteTime;
  244. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  245. type = 0;
  246. dataLen = sizeof(data);
  247. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  248. data[dataLen] = '\0';
  249. if ((!strnicmp(data,"zttap",5))&&(WINENV.tapDriverName != data)) {
  250. std::string instanceIdPath;
  251. type = 0;
  252. dataLen = sizeof(data);
  253. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  254. instanceIdPath.assign(data,dataLen);
  255. if (instanceIdPath.length() != 0)
  256. instanceIdPathsToRemove.insert(instanceIdPath);
  257. }
  258. }
  259. } else break; // end of list or failure
  260. }
  261. RegCloseKey(nwAdapters);
  262. }
  263. std::string errlist;
  264. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  265. std::string err = deletePersistentTapDevice(iidp->c_str());
  266. if (err.length() > 0) {
  267. if (errlist.length() > 0)
  268. errlist.push_back(',');
  269. errlist.append(err);
  270. }
  271. }
  272. return errlist;
  273. }
  274. std::string WindowsEthernetTap::destroyAllPersistentTapDevices()
  275. {
  276. char subkeyName[1024];
  277. char subkeyClass[1024];
  278. char data[1024];
  279. std::set<std::string> instanceIdPathsToRemove;
  280. {
  281. HKEY nwAdapters;
  282. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  283. return std::string("Could not open registry key");
  284. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  285. DWORD type;
  286. DWORD dataLen;
  287. DWORD subkeyNameLen = sizeof(subkeyName);
  288. DWORD subkeyClassLen = sizeof(subkeyClass);
  289. FILETIME lastWriteTime;
  290. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  291. type = 0;
  292. dataLen = sizeof(data);
  293. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  294. data[dataLen] = '\0';
  295. if (!strnicmp(data,"zttap",5)) {
  296. std::string instanceIdPath;
  297. type = 0;
  298. dataLen = sizeof(data);
  299. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  300. instanceIdPath.assign(data,dataLen);
  301. if (instanceIdPath.length() != 0)
  302. instanceIdPathsToRemove.insert(instanceIdPath);
  303. }
  304. }
  305. } else break; // end of list or failure
  306. }
  307. RegCloseKey(nwAdapters);
  308. }
  309. std::string errlist;
  310. for(std::set<std::string>::iterator iidp(instanceIdPathsToRemove.begin());iidp!=instanceIdPathsToRemove.end();++iidp) {
  311. std::string err = deletePersistentTapDevice(iidp->c_str());
  312. if (err.length() > 0) {
  313. if (errlist.length() > 0)
  314. errlist.push_back(',');
  315. errlist.append(err);
  316. }
  317. }
  318. return errlist;
  319. }
  320. std::string WindowsEthernetTap::deletePersistentTapDevice(const char *instanceId)
  321. {
  322. char iid[256];
  323. SP_REMOVEDEVICE_PARAMS rmdParams;
  324. memset(&rmdParams,0,sizeof(rmdParams));
  325. rmdParams.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  326. rmdParams.ClassInstallHeader.InstallFunction = DIF_REMOVE;
  327. rmdParams.Scope = DI_REMOVEDEVICE_GLOBAL;
  328. rmdParams.HwProfile = 0;
  329. Mutex::Lock _l(_systemDeviceManagementLock);
  330. HDEVINFO devInfo = WINENV.SetupDiGetClassDevsExA((const GUID *)0,(PCSTR)0,(HWND)0,DIGCF_ALLCLASSES,(HDEVINFO)0,(PCSTR)0,(PVOID)0);
  331. if (devInfo == INVALID_HANDLE_VALUE)
  332. return std::string("SetupDiGetClassDevsExA() failed");
  333. WINENV.SetupDiOpenDeviceInfoA(devInfo,instanceId,(HWND)0,0,(PSP_DEVINFO_DATA)0);
  334. SP_DEVINFO_DATA devInfoData;
  335. memset(&devInfoData,0,sizeof(devInfoData));
  336. devInfoData.cbSize = sizeof(devInfoData);
  337. for(DWORD devIndex=0;WINENV.SetupDiEnumDeviceInfo(devInfo,devIndex,&devInfoData);devIndex++) {
  338. if ((WINENV.CM_Get_Device_ID_ExA(devInfoData.DevInst,iid,sizeof(iid),0,(HMACHINE)0) == CR_SUCCESS)&&(!strcmp(iid,instanceId))) {
  339. if (!WINENV.SetupDiSetClassInstallParamsA(devInfo,&devInfoData,&rmdParams.ClassInstallHeader,sizeof(rmdParams))) {
  340. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  341. return std::string("SetupDiSetClassInstallParams() failed");
  342. }
  343. if (!WINENV.SetupDiCallClassInstaller(DIF_REMOVE,devInfo,&devInfoData)) {
  344. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  345. return std::string("SetupDiCallClassInstaller(DIF_REMOVE) failed");
  346. }
  347. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  348. return std::string();
  349. }
  350. }
  351. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  352. return std::string("instance ID not found");
  353. }
  354. bool WindowsEthernetTap::setPersistentTapDeviceState(const char *instanceId,bool enabled)
  355. {
  356. char iid[256];
  357. SP_PROPCHANGE_PARAMS params;
  358. Mutex::Lock _l(_systemDeviceManagementLock);
  359. HDEVINFO devInfo = WINENV.SetupDiGetClassDevsExA((const GUID *)0,(PCSTR)0,(HWND)0,DIGCF_ALLCLASSES,(HDEVINFO)0,(PCSTR)0,(PVOID)0);
  360. if (devInfo == INVALID_HANDLE_VALUE)
  361. return false;
  362. WINENV.SetupDiOpenDeviceInfoA(devInfo,instanceId,(HWND)0,0,(PSP_DEVINFO_DATA)0);
  363. SP_DEVINFO_DATA devInfoData;
  364. memset(&devInfoData,0,sizeof(devInfoData));
  365. devInfoData.cbSize = sizeof(devInfoData);
  366. for(DWORD devIndex=0;WINENV.SetupDiEnumDeviceInfo(devInfo,devIndex,&devInfoData);devIndex++) {
  367. if ((WINENV.CM_Get_Device_ID_ExA(devInfoData.DevInst,iid,sizeof(iid),0,(HMACHINE)0) == CR_SUCCESS)&&(!strcmp(iid,instanceId))) {
  368. memset(&params,0,sizeof(params));
  369. params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  370. params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
  371. params.StateChange = enabled ? DICS_ENABLE : DICS_DISABLE;
  372. params.Scope = DICS_FLAG_GLOBAL;
  373. params.HwProfile = 0;
  374. WINENV.SetupDiSetClassInstallParamsA(devInfo,&devInfoData,&params.ClassInstallHeader,sizeof(params));
  375. WINENV.SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,devInfo,&devInfoData);
  376. memset(&params,0,sizeof(params));
  377. params.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  378. params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE;
  379. params.StateChange = enabled ? DICS_ENABLE : DICS_DISABLE;
  380. params.Scope = DICS_FLAG_CONFIGSPECIFIC;
  381. params.HwProfile = 0;
  382. WINENV.SetupDiSetClassInstallParamsA(devInfo,&devInfoData,&params.ClassInstallHeader,sizeof(params));
  383. WINENV.SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,devInfo,&devInfoData);
  384. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  385. return true;
  386. }
  387. }
  388. WINENV.SetupDiDestroyDeviceInfoList(devInfo);
  389. return false;
  390. }
  391. WindowsEthernetTap::WindowsEthernetTap(
  392. const char *hp,
  393. const MAC &mac,
  394. unsigned int mtu,
  395. unsigned int metric,
  396. uint64_t nwid,
  397. const char *friendlyName,
  398. void (*handler)(void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int),
  399. void *arg) :
  400. _handler(handler),
  401. _arg(arg),
  402. _mac(mac),
  403. _nwid(nwid),
  404. _tap(INVALID_HANDLE_VALUE),
  405. _injectSemaphore(INVALID_HANDLE_VALUE),
  406. _pathToHelpers(hp),
  407. _run(true),
  408. _initialized(false),
  409. _enabled(true)
  410. {
  411. char subkeyName[1024];
  412. char subkeyClass[1024];
  413. char data[1024];
  414. char tag[24];
  415. std::string mySubkeyName;
  416. if (mtu > 2800)
  417. throw std::runtime_error("MTU too large.");
  418. // We "tag" registry entries with the network ID to identify persistent devices
  419. Utils::snprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)nwid);
  420. Mutex::Lock _l(_systemTapInitLock);
  421. HKEY nwAdapters;
  422. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  423. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  424. // Look for the tap instance that corresponds with this network
  425. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  426. DWORD type;
  427. DWORD dataLen;
  428. DWORD subkeyNameLen = sizeof(subkeyName);
  429. DWORD subkeyClassLen = sizeof(subkeyClass);
  430. FILETIME lastWriteTime;
  431. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  432. type = 0;
  433. dataLen = sizeof(data);
  434. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  435. data[dataLen] = (char)0;
  436. if (WINENV.tapDriverName == data) {
  437. std::string instanceId;
  438. type = 0;
  439. dataLen = sizeof(data);
  440. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  441. instanceId.assign(data,dataLen);
  442. std::string instanceIdPath;
  443. type = 0;
  444. dataLen = sizeof(data);
  445. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  446. instanceIdPath.assign(data,dataLen);
  447. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  448. type = 0;
  449. dataLen = sizeof(data);
  450. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  451. data[dataLen] = '\0';
  452. if (!strcmp(data,tag)) {
  453. _netCfgInstanceId = instanceId;
  454. _deviceInstanceId = instanceIdPath;
  455. mySubkeyName = subkeyName;
  456. break; // found it!
  457. }
  458. }
  459. }
  460. }
  461. }
  462. } else break; // no more subkeys or error occurred enumerating them
  463. }
  464. // If there is no device, try to create one
  465. bool creatingNewDevice = (_netCfgInstanceId.length() == 0);
  466. std::string newDeviceInstanceId;
  467. if (creatingNewDevice) {
  468. for(int getNewAttemptCounter=0;getNewAttemptCounter<2;++getNewAttemptCounter) {
  469. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  470. DWORD type;
  471. DWORD dataLen;
  472. DWORD subkeyNameLen = sizeof(subkeyName);
  473. DWORD subkeyClassLen = sizeof(subkeyClass);
  474. FILETIME lastWriteTime;
  475. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  476. type = 0;
  477. dataLen = sizeof(data);
  478. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  479. data[dataLen] = '\0';
  480. if (WINENV.tapDriverName == data) {
  481. type = 0;
  482. dataLen = sizeof(data);
  483. if ((RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) != ERROR_SUCCESS)||(dataLen <= 0)) {
  484. type = 0;
  485. dataLen = sizeof(data);
  486. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  487. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  488. _netCfgInstanceId.assign(data,dataLen);
  489. type = 0;
  490. dataLen = sizeof(data);
  491. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  492. _deviceInstanceId.assign(data,dataLen);
  493. mySubkeyName = subkeyName;
  494. // Disable DHCP by default on new devices
  495. HKEY tcpIpInterfaces;
  496. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  497. DWORD enable = 0;
  498. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  499. RegCloseKey(tcpIpInterfaces);
  500. }
  501. break; // found an unused zttap device
  502. }
  503. }
  504. }
  505. }
  506. } else break; // no more keys or error occurred
  507. }
  508. if (_netCfgInstanceId.length() > 0) {
  509. break; // found an unused zttap device
  510. } else {
  511. // no unused zttap devices, so create one
  512. std::string errm = addNewPersistentTapDevice((std::string(_pathToHelpers) + WINENV.tapDriverPath).c_str(),newDeviceInstanceId);
  513. if (errm.length() > 0)
  514. throw std::runtime_error(std::string("unable to create new device instance: ")+errm);
  515. }
  516. }
  517. }
  518. if (_netCfgInstanceId.length() > 0) {
  519. char tmps[64];
  520. 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;
  521. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  522. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  523. tmpsl = Utils::snprintf(tmps, sizeof(tmps), "%d", mtu);
  524. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"MTU",REG_SZ,tmps,tmpsl);
  525. DWORD tmp = 0;
  526. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"*NdisDeviceType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  527. tmp = IF_TYPE_ETHERNET_CSMACD;
  528. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"*IfType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  529. if (creatingNewDevice) {
  530. // Vista/2008 does not set this
  531. if (newDeviceInstanceId.length() > 0)
  532. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"DeviceInstanceID",REG_SZ,newDeviceInstanceId.c_str(),(DWORD)newDeviceInstanceId.length());
  533. // Set EnableDHCP to 0 by default on new devices
  534. tmp = 0;
  535. RegSetKeyValueA(nwAdapters,mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  536. }
  537. RegCloseKey(nwAdapters);
  538. } else {
  539. RegCloseKey(nwAdapters);
  540. throw std::runtime_error("unable to find or create tap adapter");
  541. }
  542. {
  543. char nobraces[128]; // strip braces from GUID before converting it, because Windows
  544. const char *nbtmp1 = _netCfgInstanceId.c_str();
  545. char *nbtmp2 = nobraces;
  546. while (*nbtmp1) {
  547. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  548. *nbtmp2++ = *nbtmp1;
  549. ++nbtmp1;
  550. }
  551. *nbtmp2 = (char)0;
  552. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  553. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  554. }
  555. // Get the LUID, which is one of like four fucking ways to refer to a network device in Windows
  556. if (ConvertInterfaceGuidToLuid(&_deviceGuid,&_deviceLuid) != NO_ERROR)
  557. throw std::runtime_error("unable to convert device interface GUID to LUID");
  558. //_initialized = true;
  559. if (friendlyName)
  560. setFriendlyName(friendlyName);
  561. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  562. _thread = Thread::start(this);
  563. }
  564. WindowsEthernetTap::~WindowsEthernetTap()
  565. {
  566. _run = false;
  567. ReleaseSemaphore(_injectSemaphore,1,NULL);
  568. Thread::join(_thread);
  569. CloseHandle(_injectSemaphore);
  570. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  571. }
  572. void WindowsEthernetTap::setEnabled(bool en)
  573. {
  574. _enabled = en;
  575. }
  576. bool WindowsEthernetTap::enabled() const
  577. {
  578. return _enabled;
  579. }
  580. bool WindowsEthernetTap::addIp(const InetAddress &ip)
  581. {
  582. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  583. return false;
  584. Mutex::Lock _l(_assignedIps_m);
  585. if (std::find(_assignedIps.begin(),_assignedIps.end(),ip) != _assignedIps.end())
  586. return true;
  587. _assignedIps.push_back(ip);
  588. _syncIps();
  589. return true;
  590. }
  591. bool WindowsEthernetTap::removeIp(const InetAddress &ip)
  592. {
  593. if (ip.isV6())
  594. return true;
  595. {
  596. Mutex::Lock _l(_assignedIps_m);
  597. std::vector<InetAddress>::iterator aip(std::find(_assignedIps.begin(),_assignedIps.end(),ip));
  598. if (aip != _assignedIps.end())
  599. _assignedIps.erase(aip);
  600. }
  601. if (!_initialized)
  602. return false;
  603. try {
  604. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  605. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  606. if ((ipt)&&(ipt->NumEntries > 0)) {
  607. for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
  608. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  609. InetAddress addr;
  610. switch(ipt->Table[i].Address.si_family) {
  611. case AF_INET:
  612. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  613. break;
  614. case AF_INET6:
  615. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  616. if (addr.ipScope() == InetAddress::IP_SCOPE_LINK_LOCAL)
  617. continue; // can't remove link-local IPv6 addresses
  618. break;
  619. }
  620. if (addr == ip) {
  621. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  622. FreeMibTable(ipt);
  623. if (ip.isV4()) {
  624. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  625. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  626. std::string ipstr(ip.toIpString());
  627. for (std::vector<std::string>::iterator rip(regIps.begin()), rm(regSubnetMasks.begin()); ((rip != regIps.end()) && (rm != regSubnetMasks.end())); ++rip, ++rm) {
  628. if (*rip == ipstr) {
  629. regIps.erase(rip);
  630. regSubnetMasks.erase(rm);
  631. _setRegistryIPv4Value("IPAddress", regIps);
  632. _setRegistryIPv4Value("SubnetMask", regSubnetMasks);
  633. break;
  634. }
  635. }
  636. }
  637. return true;
  638. }
  639. }
  640. }
  641. }
  642. FreeMibTable((PVOID)ipt);
  643. }
  644. } catch ( ... ) {}
  645. return false;
  646. }
  647. std::vector<InetAddress> WindowsEthernetTap::ips() const
  648. {
  649. static const InetAddress linkLocalLoopback("fe80::1",64); // what is this and why does Windows assign it?
  650. std::vector<InetAddress> addrs;
  651. if (!_initialized)
  652. return addrs;
  653. try {
  654. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  655. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  656. if ((ipt)&&(ipt->NumEntries > 0)) {
  657. for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
  658. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  659. switch(ipt->Table[i].Address.si_family) {
  660. case AF_INET: {
  661. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  662. if (ip != InetAddress::LO4)
  663. addrs.push_back(ip);
  664. } break;
  665. case AF_INET6: {
  666. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  667. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  668. addrs.push_back(ip);
  669. } break;
  670. }
  671. }
  672. }
  673. }
  674. FreeMibTable(ipt);
  675. }
  676. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  677. std::sort(addrs.begin(),addrs.end());
  678. addrs.erase(std::unique(addrs.begin(),addrs.end()),addrs.end());
  679. return addrs;
  680. }
  681. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  682. {
  683. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > (ZT_IF_MTU)))
  684. return;
  685. Mutex::Lock _l(_injectPending_m);
  686. _injectPending.push( std::pair<Array<char,ZT_IF_MTU + 32>,unsigned int>(Array<char,ZT_IF_MTU + 32>(),len + 14) );
  687. char *d = _injectPending.back().first.data;
  688. to.copyTo(d,6);
  689. from.copyTo(d + 6,6);
  690. d[12] = (char)((etherType >> 8) & 0xff);
  691. d[13] = (char)(etherType & 0xff);
  692. memcpy(d + 14,data,len);
  693. ReleaseSemaphore(_injectSemaphore,1,NULL);
  694. }
  695. std::string WindowsEthernetTap::deviceName() const
  696. {
  697. char tmp[1024];
  698. if (ConvertInterfaceLuidToNameA(&_deviceLuid,tmp,sizeof(tmp)) != NO_ERROR)
  699. return std::string("[ConvertInterfaceLuidToName() failed]");
  700. return std::string(tmp);
  701. }
  702. void WindowsEthernetTap::setFriendlyName(const char *dn)
  703. {
  704. if (!_initialized)
  705. return;
  706. HKEY ifp;
  707. 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) {
  708. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  709. RegCloseKey(ifp);
  710. }
  711. }
  712. void WindowsEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  713. {
  714. if (!_initialized)
  715. return;
  716. HANDLE t = _tap;
  717. if (t == INVALID_HANDLE_VALUE)
  718. return;
  719. std::vector<MulticastGroup> newGroups;
  720. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  721. // level... something Windows does not seem to expose ordinarily. This lets
  722. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  723. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  724. DWORD bytesReturned = 0;
  725. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)0,0,(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  726. if ((bytesReturned > 0)&&(bytesReturned <= TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE)) { // sanity check
  727. MAC mac;
  728. DWORD i = 0;
  729. while ((i + 6) <= bytesReturned) {
  730. mac.setTo(mcastbuf + i,6);
  731. i += 6;
  732. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  733. // exclude the nulls that may be returned or any other junk Windows puts in there
  734. newGroups.push_back(MulticastGroup(mac,0));
  735. }
  736. }
  737. }
  738. }
  739. std::vector<InetAddress> allIps(ips());
  740. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  741. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  742. std::sort(newGroups.begin(),newGroups.end());
  743. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  744. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  745. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  746. added.push_back(*m);
  747. }
  748. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  749. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  750. removed.push_back(*m);
  751. }
  752. _multicastGroups.swap(newGroups);
  753. }
  754. NET_IFINDEX WindowsEthernetTap::interfaceIndex() const
  755. {
  756. NET_IFINDEX idx = -1;
  757. if (ConvertInterfaceLuidToIndex(&_deviceLuid,&idx) == NO_ERROR)
  758. return idx;
  759. return -1;
  760. }
  761. void WindowsEthernetTap::threadMain()
  762. throw()
  763. {
  764. char tapReadBuf[ZT_IF_MTU + 32];
  765. char tapPath[128];
  766. HANDLE wait4[3];
  767. OVERLAPPED tapOvlRead,tapOvlWrite;
  768. Utils::snprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  769. try {
  770. while (_run) {
  771. // Because Windows
  772. Sleep(250);
  773. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  774. Sleep(250);
  775. setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
  776. Sleep(250);
  777. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  778. Sleep(250);
  779. setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
  780. Sleep(250);
  781. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  782. if (_tap == INVALID_HANDLE_VALUE) {
  783. Sleep(250);
  784. continue;
  785. }
  786. {
  787. uint32_t tmpi = 1;
  788. DWORD bytesReturned = 0;
  789. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  790. }
  791. #ifdef ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  792. {
  793. /* This inserts a fake default route and a fake ARP entry, forcing
  794. * Windows to detect this as a "real" network and apply proper
  795. * firewall rules.
  796. *
  797. * This hack is completely stupid, but Windows made me do it
  798. * by being broken and insane.
  799. *
  800. * Background: Windows tries to detect its network location by
  801. * matching it to the ARP address of the default route. Networks
  802. * without default routes are "unidentified networks" and cannot
  803. * have their firewall classification changed by the user (easily).
  804. *
  805. * Yes, you read that right.
  806. *
  807. * The common workaround is to set *NdisDeviceType to 1, which
  808. * totally disables all Windows firewall functionality. This is
  809. * the answer you'll find on most forums for things like OpenVPN.
  810. *
  811. * Yes, you read that right.
  812. *
  813. * The default route workaround is also known, but for this to
  814. * work there must be a known default IP that resolves to a known
  815. * ARP address. This works for an OpenVPN tunnel, but not here
  816. * because this isn't a tunnel. It's a mesh. There is no "other
  817. * end," or any other known always on IP.
  818. *
  819. * So let's make a fake one and shove it in there along with its
  820. * fake static ARP entry. Also makes it instant-on and static.
  821. *
  822. * We'll have to see what DHCP does with this. In the future we
  823. * probably will not want to do this on DHCP-enabled networks, so
  824. * when we enable DHCP we will go in and yank this wacko hacko from
  825. * the routing table before doing so.
  826. *
  827. * Like Jesse Pinkman would say: "YEEEEAAH BITCH!" */
  828. const uint32_t fakeIp = htonl(0x19fffffe); // 25.255.255.254 -- unrouted IPv4 block
  829. for(int i=0;i<8;++i) {
  830. MIB_IPNET_ROW2 ipnr;
  831. memset(&ipnr,0,sizeof(ipnr));
  832. ipnr.Address.si_family = AF_INET;
  833. ipnr.Address.Ipv4.sin_addr.s_addr = fakeIp;
  834. ipnr.InterfaceLuid.Value = _deviceLuid.Value;
  835. ipnr.PhysicalAddress[0] = _mac[0] ^ 0x10; // just make something up that's consistent and not part of this net
  836. ipnr.PhysicalAddress[1] = 0x00;
  837. ipnr.PhysicalAddress[2] = (UCHAR)((_deviceGuid.Data1 >> 24) & 0xff);
  838. ipnr.PhysicalAddress[3] = (UCHAR)((_deviceGuid.Data1 >> 16) & 0xff);
  839. ipnr.PhysicalAddress[4] = (UCHAR)((_deviceGuid.Data1 >> 8) & 0xff);
  840. ipnr.PhysicalAddress[5] = (UCHAR)(_deviceGuid.Data1 & 0xff);
  841. ipnr.PhysicalAddressLength = 6;
  842. ipnr.State = NlnsPermanent;
  843. ipnr.IsRouter = 1;
  844. ipnr.IsUnreachable = 0;
  845. ipnr.ReachabilityTime.LastReachable = 0x0fffffff;
  846. ipnr.ReachabilityTime.LastUnreachable = 1;
  847. DWORD result = CreateIpNetEntry2(&ipnr);
  848. if (result != NO_ERROR)
  849. Sleep(250);
  850. else break;
  851. }
  852. for(int i=0;i<8;++i) {
  853. MIB_IPFORWARD_ROW2 nr;
  854. memset(&nr,0,sizeof(nr));
  855. InitializeIpForwardEntry(&nr);
  856. nr.InterfaceLuid.Value = _deviceLuid.Value;
  857. nr.DestinationPrefix.Prefix.si_family = AF_INET; // rest is left as 0.0.0.0/0
  858. nr.NextHop.si_family = AF_INET;
  859. nr.NextHop.Ipv4.sin_addr.s_addr = fakeIp;
  860. nr.Metric = 9999; // do not use as real default route
  861. nr.Protocol = MIB_IPPROTO_NETMGMT;
  862. DWORD result = CreateIpForwardEntry2(&nr);
  863. if (result != NO_ERROR)
  864. Sleep(250);
  865. else break;
  866. }
  867. }
  868. #endif
  869. // Assign or re-assign any should-be-assigned IPs in case we have restarted
  870. {
  871. Mutex::Lock _l(_assignedIps_m);
  872. _syncIps();
  873. }
  874. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  875. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  876. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  877. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  878. wait4[0] = _injectSemaphore;
  879. wait4[1] = tapOvlRead.hEvent;
  880. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  881. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  882. bool writeInProgress = false;
  883. ULONGLONG timeOfLastBorkCheck = GetTickCount64();
  884. _initialized = true;
  885. while (_run) {
  886. DWORD waitResult = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,2500,TRUE);
  887. if (!_run) break; // will also break outer while(_run)
  888. // Check for issues with adapter and close/reopen if any are detected. This
  889. // check fixes a while boatload of Windows adapter 'coma' issues after
  890. // sleep/wake and when adapters are added/removed. Basically if the tap
  891. // device is borked, whack it.
  892. {
  893. ULONGLONG tc = GetTickCount64();
  894. if ((tc - timeOfLastBorkCheck) >= 2500) {
  895. timeOfLastBorkCheck = tc;
  896. char aabuf[16384];
  897. ULONG aalen = sizeof(aabuf);
  898. if (GetAdaptersAddresses(AF_UNSPEC,GAA_FLAG_SKIP_UNICAST|GAA_FLAG_SKIP_ANYCAST|GAA_FLAG_SKIP_MULTICAST|GAA_FLAG_SKIP_DNS_SERVER|GAA_FLAG_SKIP_FRIENDLY_NAME,(void *)0,reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf),&aalen) == NO_ERROR) {
  899. bool isBorked = false;
  900. PIP_ADAPTER_ADDRESSES aa = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  901. while (aa) {
  902. if (_deviceLuid.Value == aa->Luid.Value) {
  903. isBorked = (aa->OperStatus != IfOperStatusUp);
  904. break;
  905. }
  906. aa = aa->Next;
  907. }
  908. if (isBorked) {
  909. // Close and reopen tap device if there's an issue (outer loop)
  910. break;
  911. }
  912. }
  913. }
  914. }
  915. if ((waitResult == WAIT_TIMEOUT)||(waitResult == WAIT_FAILED)) {
  916. Sleep(250); // guard against spinning under some conditions
  917. continue;
  918. }
  919. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  920. DWORD bytesRead = 0;
  921. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  922. if ((bytesRead > 14)&&(_enabled)) {
  923. MAC to(tapReadBuf,6);
  924. MAC from(tapReadBuf + 6,6);
  925. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  926. try {
  927. // TODO: decode vlans
  928. _handler(_arg,_nwid,from,to,etherType,0,tapReadBuf + 14,bytesRead - 14);
  929. } catch ( ... ) {} // handlers should not throw
  930. }
  931. }
  932. ReadFile(_tap,tapReadBuf,ZT_IF_MTU + 32,NULL,&tapOvlRead);
  933. }
  934. if (writeInProgress) {
  935. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  936. writeInProgress = false;
  937. _injectPending_m.lock();
  938. _injectPending.pop();
  939. } else continue; // still writing, so skip code below and wait
  940. } else _injectPending_m.lock();
  941. if (!_injectPending.empty()) {
  942. WriteFile(_tap,_injectPending.front().first.data,_injectPending.front().second,NULL,&tapOvlWrite);
  943. writeInProgress = true;
  944. }
  945. _injectPending_m.unlock();
  946. }
  947. CancelIo(_tap);
  948. CloseHandle(tapOvlRead.hEvent);
  949. CloseHandle(tapOvlWrite.hEvent);
  950. CloseHandle(_tap);
  951. _tap = INVALID_HANDLE_VALUE;
  952. // We will restart and re-open the tap unless _run == false
  953. }
  954. } catch ( ... ) {} // catch unexpected exceptions -- this should not happen but would prevent program crash or other weird issues since threads should not throw
  955. }
  956. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  957. {
  958. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  959. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  960. throw std::runtime_error("GetIfTable2Ex() failed");
  961. if (ift->NumEntries > 0) {
  962. for(ULONG i=0;i<ift->NumEntries;++i) {
  963. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  964. NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
  965. FreeMibTable(ift);
  966. return idx;
  967. }
  968. }
  969. }
  970. FreeMibTable(&ift);
  971. throw std::runtime_error("interface not found");
  972. }
  973. std::vector<std::string> WindowsEthernetTap::_getRegistryIPv4Value(const char *regKey)
  974. {
  975. std::vector<std::string> value;
  976. HKEY tcpIpInterfaces;
  977. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  978. char buf[16384];
  979. DWORD len = sizeof(buf);
  980. DWORD kt = REG_MULTI_SZ;
  981. if (RegGetValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,0,&kt,&buf,&len) == ERROR_SUCCESS) {
  982. switch(kt) {
  983. case REG_SZ:
  984. if (len > 0)
  985. value.push_back(std::string(buf));
  986. break;
  987. case REG_MULTI_SZ: {
  988. for(DWORD k=0,s=0;k<len;++k) {
  989. if (!buf[k]) {
  990. if (s < k) {
  991. value.push_back(std::string(buf + s));
  992. s = k + 1;
  993. } else break;
  994. }
  995. }
  996. } break;
  997. }
  998. }
  999. RegCloseKey(tcpIpInterfaces);
  1000. }
  1001. return value;
  1002. }
  1003. void WindowsEthernetTap::_setRegistryIPv4Value(const char *regKey,const std::vector<std::string> &value)
  1004. {
  1005. std::string regMulti;
  1006. for(std::vector<std::string>::const_iterator s(value.begin());s!=value.end();++s) {
  1007. regMulti.append(*s);
  1008. regMulti.push_back((char)0);
  1009. }
  1010. HKEY tcpIpInterfaces;
  1011. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  1012. if (regMulti.length() > 0) {
  1013. regMulti.push_back((char)0);
  1014. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,REG_MULTI_SZ,regMulti.data(),(DWORD)regMulti.length());
  1015. } else {
  1016. RegDeleteKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey);
  1017. }
  1018. RegCloseKey(tcpIpInterfaces);
  1019. }
  1020. }
  1021. void WindowsEthernetTap::_syncIps()
  1022. {
  1023. // assumes _assignedIps_m is locked
  1024. if (!_initialized)
  1025. return;
  1026. std::vector<InetAddress> haveIps(ips());
  1027. for(std::vector<InetAddress>::const_iterator aip(_assignedIps.begin());aip!=_assignedIps.end();++aip) {
  1028. if (std::find(haveIps.begin(),haveIps.end(),*aip) == haveIps.end()) {
  1029. MIB_UNICASTIPADDRESS_ROW ipr;
  1030. InitializeUnicastIpAddressEntry(&ipr);
  1031. if (aip->isV4()) {
  1032. ipr.Address.Ipv4.sin_family = AF_INET;
  1033. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)aip->rawIpData());
  1034. ipr.OnLinkPrefixLength = aip->netmaskBits();
  1035. if (ipr.OnLinkPrefixLength >= 32)
  1036. continue;
  1037. } else if (aip->isV6()) {
  1038. ipr.Address.Ipv6.sin6_family = AF_INET6;
  1039. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,aip->rawIpData(),16);
  1040. ipr.OnLinkPrefixLength = aip->netmaskBits();
  1041. if (ipr.OnLinkPrefixLength >= 128)
  1042. continue;
  1043. } else continue;
  1044. ipr.PrefixOrigin = IpPrefixOriginManual;
  1045. ipr.SuffixOrigin = IpSuffixOriginManual;
  1046. ipr.ValidLifetime = 0xffffffff;
  1047. ipr.PreferredLifetime = 0xffffffff;
  1048. ipr.InterfaceLuid = _deviceLuid;
  1049. ipr.InterfaceIndex = _getDeviceIndex();
  1050. CreateUnicastIpAddressEntry(&ipr);
  1051. }
  1052. if (aip->isV4())
  1053. {
  1054. std::string ipStr(aip->toIpString());
  1055. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  1056. if (std::find(regIps.begin(), regIps.end(), ipStr) == regIps.end()) {
  1057. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  1058. regIps.push_back(ipStr);
  1059. regSubnetMasks.push_back(aip->netmask().toIpString());
  1060. _setRegistryIPv4Value("IPAddress", regIps);
  1061. _setRegistryIPv4Value("SubnetMask", regSubnetMasks);
  1062. }
  1063. }
  1064. }
  1065. }
  1066. } // namespace ZeroTier