WindowsEthernetTap.cpp 47 KB

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