WindowsEthernetTap.cpp 45 KB

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