WindowsEthernetTap.cpp 46 KB

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