WindowsEthernetTap.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  1. /*
  2. * ZeroTier One - Network Virtualization Everywhere
  3. * Copyright (C) 2011-2019 ZeroTier, Inc. https://www.zerotier.com/
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. * --
  19. *
  20. * You can be released from the requirements of the license by purchasing
  21. * a commercial license. Buying such a license is mandatory as soon as you
  22. * develop commercial closed-source software that incorporates or links
  23. * directly against ZeroTier software without disclosing the source code
  24. * of your own application.
  25. */
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <stdint.h>
  29. #include <string.h>
  30. #include <WinSock2.h>
  31. #include <Windows.h>
  32. #include <tchar.h>
  33. #include <malloc.h>
  34. #include <winreg.h>
  35. #include <wchar.h>
  36. #include <ws2ipdef.h>
  37. #include <WS2tcpip.h>
  38. #include <IPHlpApi.h>
  39. #include <nldef.h>
  40. #include <netioapi.h>
  41. #include <atlbase.h>
  42. #include <netlistmgr.h>
  43. #include <nldef.h>
  44. #include <SetupAPI.h>
  45. #include <newdev.h>
  46. #include <cfgmgr32.h>
  47. #include <iostream>
  48. #include <set>
  49. #include "../node/Constants.hpp"
  50. #include "../node/Utils.hpp"
  51. #include "../node/Mutex.hpp"
  52. #include "WindowsEthernetTap.hpp"
  53. #include "OSUtils.hpp"
  54. #include "..\windows\TapDriver6\tap-windows.h"
  55. #include <netcon.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[1024];
  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[1024];
  240. char subkeyClass[1024];
  241. char data[1024];
  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[1024];
  286. char subkeyClass[1024];
  287. char data[1024];
  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 *,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. _mtu(mtu),
  414. _tap(INVALID_HANDLE_VALUE),
  415. _friendlyName(friendlyName),
  416. _injectSemaphore(INVALID_HANDLE_VALUE),
  417. _pathToHelpers(hp),
  418. _run(true),
  419. _initialized(false),
  420. _enabled(true)
  421. {
  422. char subkeyName[1024];
  423. char subkeyClass[1024];
  424. char data[1024];
  425. char tag[24];
  426. // We "tag" registry entries with the network ID to identify persistent devices
  427. OSUtils::ztsnprintf(tag,sizeof(tag),"%.16llx",(unsigned long long)nwid);
  428. Mutex::Lock _l(_systemTapInitLock);
  429. HKEY nwAdapters;
  430. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}",0,KEY_READ|KEY_WRITE,&nwAdapters) != ERROR_SUCCESS)
  431. throw std::runtime_error("unable to open registry key for network adapter enumeration");
  432. // Look for the tap instance that corresponds with this network
  433. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  434. DWORD type;
  435. DWORD dataLen;
  436. DWORD subkeyNameLen = sizeof(subkeyName);
  437. DWORD subkeyClassLen = sizeof(subkeyClass);
  438. FILETIME lastWriteTime;
  439. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  440. type = 0;
  441. dataLen = sizeof(data);
  442. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  443. data[dataLen] = (char)0;
  444. if (WINENV.tapDriverName == data) {
  445. std::string instanceId;
  446. type = 0;
  447. dataLen = sizeof(data);
  448. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  449. instanceId.assign(data,dataLen);
  450. std::string instanceIdPath;
  451. type = 0;
  452. dataLen = sizeof(data);
  453. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  454. instanceIdPath.assign(data,dataLen);
  455. if ((_netCfgInstanceId.length() == 0)&&(instanceId.length() != 0)&&(instanceIdPath.length() != 0)) {
  456. type = 0;
  457. dataLen = sizeof(data);
  458. if (RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  459. data[dataLen] = '\0';
  460. if (!strcmp(data,tag)) {
  461. _netCfgInstanceId = instanceId;
  462. _deviceInstanceId = instanceIdPath;
  463. _mySubkeyName = subkeyName;
  464. break; // found it!
  465. }
  466. }
  467. }
  468. }
  469. }
  470. } else break; // no more subkeys or error occurred enumerating them
  471. }
  472. // If there is no device, try to create one
  473. bool creatingNewDevice = (_netCfgInstanceId.length() == 0);
  474. std::string newDeviceInstanceId;
  475. if (creatingNewDevice) {
  476. for(int getNewAttemptCounter=0;getNewAttemptCounter<2;++getNewAttemptCounter) {
  477. for(DWORD subkeyIndex=0;;++subkeyIndex) {
  478. DWORD type;
  479. DWORD dataLen;
  480. DWORD subkeyNameLen = sizeof(subkeyName);
  481. DWORD subkeyClassLen = sizeof(subkeyClass);
  482. FILETIME lastWriteTime;
  483. if (RegEnumKeyExA(nwAdapters,subkeyIndex,subkeyName,&subkeyNameLen,(DWORD *)0,subkeyClass,&subkeyClassLen,&lastWriteTime) == ERROR_SUCCESS) {
  484. type = 0;
  485. dataLen = sizeof(data);
  486. if (RegGetValueA(nwAdapters,subkeyName,"ComponentId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  487. data[dataLen] = '\0';
  488. if (WINENV.tapDriverName == data) {
  489. type = 0;
  490. dataLen = sizeof(data);
  491. if ((RegGetValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",RRF_RT_ANY,&type,(PVOID)data,&dataLen) != ERROR_SUCCESS)||(dataLen <= 0)) {
  492. type = 0;
  493. dataLen = sizeof(data);
  494. if (RegGetValueA(nwAdapters,subkeyName,"NetCfgInstanceId",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS) {
  495. RegSetKeyValueA(nwAdapters,subkeyName,"_ZeroTierTapIdentifier",REG_SZ,tag,(DWORD)(strlen(tag)+1));
  496. _netCfgInstanceId.assign(data,dataLen);
  497. type = 0;
  498. dataLen = sizeof(data);
  499. if (RegGetValueA(nwAdapters,subkeyName,"DeviceInstanceID",RRF_RT_ANY,&type,(PVOID)data,&dataLen) == ERROR_SUCCESS)
  500. _deviceInstanceId.assign(data,dataLen);
  501. _mySubkeyName = subkeyName;
  502. // Disable DHCP by default on new devices
  503. HKEY tcpIpInterfaces;
  504. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  505. DWORD enable = 0;
  506. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),"EnableDHCP",REG_DWORD,&enable,sizeof(enable));
  507. RegCloseKey(tcpIpInterfaces);
  508. }
  509. break; // found an unused zttap device
  510. }
  511. }
  512. }
  513. }
  514. } else break; // no more keys or error occurred
  515. }
  516. if (_netCfgInstanceId.length() > 0) {
  517. break; // found an unused zttap device
  518. } else {
  519. // no unused zttap devices, so create one
  520. std::string errm = addNewPersistentTapDevice((std::string(_pathToHelpers) + WINENV.tapDriverPath).c_str(),newDeviceInstanceId);
  521. if (errm.length() > 0)
  522. throw std::runtime_error(std::string("unable to create new device instance: ")+errm);
  523. }
  524. }
  525. }
  526. if (_netCfgInstanceId.length() > 0) {
  527. char tmps[64];
  528. 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;
  529. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"NetworkAddress",REG_SZ,tmps,tmpsl);
  530. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"MAC",REG_SZ,tmps,tmpsl);
  531. tmpsl = OSUtils::ztsnprintf(tmps, sizeof(tmps), "%d", mtu);
  532. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"MTU",REG_SZ,tmps,tmpsl);
  533. DWORD tmp = 0;
  534. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"*NdisDeviceType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  535. tmp = IF_TYPE_ETHERNET_CSMACD;
  536. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"*IfType",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  537. if (creatingNewDevice) {
  538. // Vista/2008 does not set this
  539. if (newDeviceInstanceId.length() > 0)
  540. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"DeviceInstanceID",REG_SZ,newDeviceInstanceId.c_str(),(DWORD)newDeviceInstanceId.length());
  541. // Set EnableDHCP to 0 by default on new devices
  542. tmp = 0;
  543. RegSetKeyValueA(nwAdapters,_mySubkeyName.c_str(),"EnableDHCP",REG_DWORD,(LPCVOID)&tmp,sizeof(tmp));
  544. }
  545. RegCloseKey(nwAdapters);
  546. } else {
  547. RegCloseKey(nwAdapters);
  548. throw std::runtime_error("unable to find or create tap adapter");
  549. }
  550. {
  551. char nobraces[128]; // strip braces from GUID before converting it, because Windows
  552. const char *nbtmp1 = _netCfgInstanceId.c_str();
  553. char *nbtmp2 = nobraces;
  554. while (*nbtmp1) {
  555. if ((*nbtmp1 != '{')&&(*nbtmp1 != '}'))
  556. *nbtmp2++ = *nbtmp1;
  557. ++nbtmp1;
  558. }
  559. *nbtmp2 = (char)0;
  560. if (UuidFromStringA((RPC_CSTR)nobraces,&_deviceGuid) != RPC_S_OK)
  561. throw std::runtime_error("unable to convert instance ID GUID to native GUID (invalid NetCfgInstanceId in registry?)");
  562. }
  563. // Get the LUID, which is one of like four fucking ways to refer to a network device in Windows
  564. if (ConvertInterfaceGuidToLuid(&_deviceGuid,&_deviceLuid) != NO_ERROR)
  565. throw std::runtime_error("unable to convert device interface GUID to LUID");
  566. //_initialized = true;
  567. if (friendlyName)
  568. setFriendlyName(friendlyName);
  569. _injectSemaphore = CreateSemaphore(NULL,0,1,NULL);
  570. _thread = Thread::start(this);
  571. }
  572. WindowsEthernetTap::~WindowsEthernetTap()
  573. {
  574. _run = false;
  575. ReleaseSemaphore(_injectSemaphore,1,NULL);
  576. Thread::join(_thread);
  577. CloseHandle(_injectSemaphore);
  578. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  579. }
  580. void WindowsEthernetTap::setEnabled(bool en)
  581. {
  582. _enabled = en;
  583. }
  584. bool WindowsEthernetTap::enabled() const
  585. {
  586. return _enabled;
  587. }
  588. bool WindowsEthernetTap::addIp(const InetAddress &ip)
  589. {
  590. if (!ip.netmaskBits()) // sanity check... netmask of 0.0.0.0 is WUT?
  591. return false;
  592. Mutex::Lock _l(_assignedIps_m);
  593. if (std::find(_assignedIps.begin(),_assignedIps.end(),ip) != _assignedIps.end())
  594. return true;
  595. _assignedIps.push_back(ip);
  596. _syncIps();
  597. return true;
  598. }
  599. bool WindowsEthernetTap::removeIp(const InetAddress &ip)
  600. {
  601. if (ip.isV6())
  602. return true;
  603. {
  604. Mutex::Lock _l(_assignedIps_m);
  605. std::vector<InetAddress>::iterator aip(std::find(_assignedIps.begin(),_assignedIps.end(),ip));
  606. if (aip != _assignedIps.end())
  607. _assignedIps.erase(aip);
  608. }
  609. if (!_initialized)
  610. return false;
  611. try {
  612. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  613. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  614. if ((ipt)&&(ipt->NumEntries > 0)) {
  615. for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
  616. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  617. InetAddress addr;
  618. switch(ipt->Table[i].Address.si_family) {
  619. case AF_INET:
  620. addr.set(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  621. break;
  622. case AF_INET6:
  623. addr.set(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  624. if (addr.ipScope() == InetAddress::IP_SCOPE_LINK_LOCAL)
  625. continue; // can't remove link-local IPv6 addresses
  626. break;
  627. }
  628. if (addr == ip) {
  629. DeleteUnicastIpAddressEntry(&(ipt->Table[i]));
  630. FreeMibTable(ipt);
  631. if (ip.isV4()) {
  632. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  633. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  634. char ipbuf[64];
  635. std::string ipstr(ip.toIpString(ipbuf));
  636. for (std::vector<std::string>::iterator rip(regIps.begin()), rm(regSubnetMasks.begin()); ((rip != regIps.end()) && (rm != regSubnetMasks.end())); ++rip, ++rm) {
  637. if (*rip == ipstr) {
  638. regIps.erase(rip);
  639. regSubnetMasks.erase(rm);
  640. _setRegistryIPv4Value("IPAddress", regIps);
  641. _setRegistryIPv4Value("SubnetMask", regSubnetMasks);
  642. break;
  643. }
  644. }
  645. }
  646. return true;
  647. }
  648. }
  649. }
  650. }
  651. FreeMibTable((PVOID)ipt);
  652. }
  653. } catch ( ... ) {}
  654. return false;
  655. }
  656. std::vector<InetAddress> WindowsEthernetTap::ips() const
  657. {
  658. static const InetAddress linkLocalLoopback("fe80::1/64"); // what is this and why does Windows assign it?
  659. std::vector<InetAddress> addrs;
  660. if (!_initialized)
  661. return addrs;
  662. try {
  663. MIB_UNICASTIPADDRESS_TABLE *ipt = (MIB_UNICASTIPADDRESS_TABLE *)0;
  664. if (GetUnicastIpAddressTable(AF_UNSPEC,&ipt) == NO_ERROR) {
  665. if ((ipt)&&(ipt->NumEntries > 0)) {
  666. for(DWORD i=0;i<(DWORD)ipt->NumEntries;++i) {
  667. if (ipt->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  668. switch(ipt->Table[i].Address.si_family) {
  669. case AF_INET: {
  670. InetAddress ip(&(ipt->Table[i].Address.Ipv4.sin_addr.S_un.S_addr),4,ipt->Table[i].OnLinkPrefixLength);
  671. if (ip != InetAddress::LO4)
  672. addrs.push_back(ip);
  673. } break;
  674. case AF_INET6: {
  675. InetAddress ip(ipt->Table[i].Address.Ipv6.sin6_addr.u.Byte,16,ipt->Table[i].OnLinkPrefixLength);
  676. if ((ip != linkLocalLoopback)&&(ip != InetAddress::LO6))
  677. addrs.push_back(ip);
  678. } break;
  679. }
  680. }
  681. }
  682. }
  683. FreeMibTable(ipt);
  684. }
  685. } catch ( ... ) {} // sanity check, shouldn't happen unless out of memory
  686. std::sort(addrs.begin(),addrs.end());
  687. addrs.erase(std::unique(addrs.begin(),addrs.end()),addrs.end());
  688. return addrs;
  689. }
  690. void WindowsEthernetTap::put(const MAC &from,const MAC &to,unsigned int etherType,const void *data,unsigned int len)
  691. {
  692. if ((!_initialized)||(!_enabled)||(_tap == INVALID_HANDLE_VALUE)||(len > _mtu))
  693. return;
  694. Mutex::Lock _l(_injectPending_m);
  695. _injectPending.emplace();
  696. _injectPending.back().len = len + 14;
  697. char *const d = _injectPending.back().data;
  698. to.copyTo(d,6);
  699. from.copyTo(d + 6,6);
  700. d[12] = (char)((etherType >> 8) & 0xff);
  701. d[13] = (char)(etherType & 0xff);
  702. memcpy(d + 14,data,len);
  703. ReleaseSemaphore(_injectSemaphore,1,NULL);
  704. }
  705. std::string WindowsEthernetTap::deviceName() const
  706. {
  707. char tmp[1024];
  708. if (ConvertInterfaceLuidToNameA(&_deviceLuid,tmp,sizeof(tmp)) != NO_ERROR)
  709. return std::string("[ConvertInterfaceLuidToName() failed]");
  710. return std::string(tmp);
  711. }
  712. void WindowsEthernetTap::setFriendlyName(const char *dn)
  713. {
  714. if (!_initialized)
  715. return;
  716. HKEY ifp;
  717. 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) {
  718. RegSetKeyValueA(ifp,"Connection","Name",REG_SZ,(LPCVOID)dn,(DWORD)(strlen(dn)+1));
  719. RegCloseKey(ifp);
  720. }
  721. HRESULT hr = CoInitialize(nullptr);
  722. if (hr != S_OK) return;
  723. CoInitializeSecurity(NULL, -1, NULL, NULL,
  724. RPC_C_AUTHN_LEVEL_PKT,
  725. RPC_C_IMP_LEVEL_IMPERSONATE,
  726. NULL, EOAC_NONE, NULL);
  727. if (hr != S_OK) return;
  728. INetSharingManager *nsm;
  729. hr = CoCreateInstance(__uuidof(NetSharingManager), NULL, CLSCTX_ALL, __uuidof(INetSharingManager), (void**)&nsm);
  730. if (hr != S_OK) return;
  731. bool found = false;
  732. INetSharingEveryConnectionCollection *nsecc = nullptr;
  733. hr = nsm->get_EnumEveryConnection(&nsecc);
  734. if (!nsecc) {
  735. fprintf(stderr, "Failed to get NSM connections");
  736. return;
  737. }
  738. IEnumVARIANT *ev = nullptr;
  739. IUnknown *unk = nullptr;
  740. hr = nsecc->get__NewEnum(&unk);
  741. if (unk) {
  742. hr = unk->QueryInterface(__uuidof(IEnumVARIANT), (void**)&ev);
  743. unk->Release();
  744. }
  745. if (ev) {
  746. VARIANT v;
  747. VariantInit(&v);
  748. while ((S_OK == ev->Next(1, &v, NULL)) && found == FALSE) {
  749. if (V_VT(&v) == VT_UNKNOWN) {
  750. INetConnection *nc = nullptr;
  751. V_UNKNOWN(&v)->QueryInterface(__uuidof(INetConnection), (void**)&nc);
  752. if (nc) {
  753. NETCON_PROPERTIES *ncp = nullptr;
  754. nc->GetProperties(&ncp);
  755. GUID curId = ncp->guidId;
  756. if (curId == _deviceGuid) {
  757. wchar_t wtext[255];
  758. mbstowcs(wtext, dn, strlen(dn)+1);
  759. nc->Rename(wtext);
  760. found = true;
  761. }
  762. nc->Release();
  763. }
  764. }
  765. VariantClear(&v);
  766. }
  767. ev->Release();
  768. }
  769. nsecc->Release();
  770. }
  771. void WindowsEthernetTap::scanMulticastGroups(std::vector<MulticastGroup> &added,std::vector<MulticastGroup> &removed)
  772. {
  773. if (!_initialized)
  774. return;
  775. HANDLE t = _tap;
  776. if (t == INVALID_HANDLE_VALUE)
  777. return;
  778. std::vector<MulticastGroup> newGroups;
  779. // The ZT1 tap driver supports an IOCTL to get multicast memberships at the L2
  780. // level... something Windows does not seem to expose ordinarily. This lets
  781. // pretty much anything work... IPv4, IPv6, IPX, oldskool Netbios, who knows...
  782. unsigned char mcastbuf[TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE];
  783. DWORD bytesReturned = 0;
  784. if (DeviceIoControl(t,TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS,(LPVOID)mcastbuf,sizeof(mcastbuf),(LPVOID)mcastbuf,sizeof(mcastbuf),&bytesReturned,NULL)) {
  785. if ((bytesReturned > 0)&&(bytesReturned <= TAP_WIN_IOCTL_GET_MULTICAST_MEMBERSHIPS_OUTPUT_BUF_SIZE)) { // sanity check
  786. MAC mac;
  787. DWORD i = 0;
  788. while ((i + 6) <= bytesReturned) {
  789. mac.setTo(mcastbuf + i,6);
  790. i += 6;
  791. if ((mac.isMulticast())&&(!mac.isBroadcast())) {
  792. // exclude the nulls that may be returned or any other junk Windows puts in there
  793. newGroups.push_back(MulticastGroup(mac,0));
  794. }
  795. }
  796. }
  797. }
  798. std::vector<InetAddress> allIps(ips());
  799. for(std::vector<InetAddress>::iterator ip(allIps.begin());ip!=allIps.end();++ip)
  800. newGroups.push_back(MulticastGroup::deriveMulticastGroupForAddressResolution(*ip));
  801. std::sort(newGroups.begin(),newGroups.end());
  802. newGroups.erase(std::unique(newGroups.begin(),newGroups.end()),newGroups.end());
  803. for(std::vector<MulticastGroup>::iterator m(newGroups.begin());m!=newGroups.end();++m) {
  804. if (!std::binary_search(_multicastGroups.begin(),_multicastGroups.end(),*m))
  805. added.push_back(*m);
  806. }
  807. for(std::vector<MulticastGroup>::iterator m(_multicastGroups.begin());m!=_multicastGroups.end();++m) {
  808. if (!std::binary_search(newGroups.begin(),newGroups.end(),*m))
  809. removed.push_back(*m);
  810. }
  811. _multicastGroups.swap(newGroups);
  812. }
  813. void WindowsEthernetTap::setMtu(unsigned int mtu)
  814. {
  815. if (mtu != _mtu) {
  816. _mtu = mtu;
  817. HKEY nwAdapters;
  818. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}", 0, KEY_READ | KEY_WRITE, &nwAdapters) == ERROR_SUCCESS) {
  819. char tmps[64];
  820. unsigned int tmpsl = OSUtils::ztsnprintf(tmps, sizeof(tmps), "%d", mtu);
  821. RegSetKeyValueA(nwAdapters, _mySubkeyName.c_str(), "MTU", REG_SZ, tmps, tmpsl);
  822. RegCloseKey(nwAdapters);
  823. }
  824. }
  825. }
  826. NET_IFINDEX WindowsEthernetTap::interfaceIndex() const
  827. {
  828. NET_IFINDEX idx = -1;
  829. if (ConvertInterfaceLuidToIndex(&_deviceLuid,&idx) == NO_ERROR)
  830. return idx;
  831. return -1;
  832. }
  833. void WindowsEthernetTap::threadMain()
  834. throw()
  835. {
  836. char tapReadBuf[ZT_MAX_MTU + 32];
  837. char tapPath[128];
  838. HANDLE wait4[3];
  839. OVERLAPPED tapOvlRead,tapOvlWrite;
  840. OSUtils::ztsnprintf(tapPath,sizeof(tapPath),"\\\\.\\Global\\%s.tap",_netCfgInstanceId.c_str());
  841. try {
  842. while (_run) {
  843. // Because Windows
  844. Sleep(250);
  845. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  846. Sleep(250);
  847. setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
  848. Sleep(250);
  849. setPersistentTapDeviceState(_deviceInstanceId.c_str(),false);
  850. Sleep(250);
  851. setPersistentTapDeviceState(_deviceInstanceId.c_str(),true);
  852. Sleep(250);
  853. _tap = CreateFileA(tapPath,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_SYSTEM|FILE_FLAG_OVERLAPPED,NULL);
  854. if (_tap == INVALID_HANDLE_VALUE) {
  855. Sleep(250);
  856. continue;
  857. }
  858. {
  859. uint32_t tmpi = 1;
  860. DWORD bytesReturned = 0;
  861. DeviceIoControl(_tap,TAP_WIN_IOCTL_SET_MEDIA_STATUS,&tmpi,sizeof(tmpi),&tmpi,sizeof(tmpi),&bytesReturned,NULL);
  862. }
  863. #ifdef ZT_WINDOWS_CREATE_FAKE_DEFAULT_ROUTE
  864. {
  865. /* This inserts a fake default route and a fake ARP entry, forcing
  866. * Windows to detect this as a "real" network and apply proper
  867. * firewall rules.
  868. *
  869. * This hack is completely stupid, but Windows made me do it
  870. * by being broken and insane.
  871. *
  872. * Background: Windows tries to detect its network location by
  873. * matching it to the ARP address of the default route. Networks
  874. * without default routes are "unidentified networks" and cannot
  875. * have their firewall classification changed by the user (easily).
  876. *
  877. * Yes, you read that right.
  878. *
  879. * The common workaround is to set *NdisDeviceType to 1, which
  880. * totally disables all Windows firewall functionality. This is
  881. * the answer you'll find on most forums for things like OpenVPN.
  882. *
  883. * Yes, you read that right.
  884. *
  885. * The default route workaround is also known, but for this to
  886. * work there must be a known default IP that resolves to a known
  887. * ARP address. This works for an OpenVPN tunnel, but not here
  888. * because this isn't a tunnel. It's a mesh. There is no "other
  889. * end," or any other known always on IP.
  890. *
  891. * So let's make a fake one and shove it in there along with its
  892. * fake static ARP entry. Also makes it instant-on and static.
  893. *
  894. * We'll have to see what DHCP does with this. In the future we
  895. * probably will not want to do this on DHCP-enabled networks, so
  896. * when we enable DHCP we will go in and yank this wacko hacko from
  897. * the routing table before doing so.
  898. *
  899. * Like Jesse Pinkman would say: "YEEEEAAH BITCH!" */
  900. const uint32_t fakeIp = htonl(0x19fffffe); // 25.255.255.254 -- unrouted IPv4 block
  901. for(int i=0;i<8;++i) {
  902. MIB_IPNET_ROW2 ipnr;
  903. memset(&ipnr,0,sizeof(ipnr));
  904. ipnr.Address.si_family = AF_INET;
  905. ipnr.Address.Ipv4.sin_addr.s_addr = fakeIp;
  906. ipnr.InterfaceLuid.Value = _deviceLuid.Value;
  907. ipnr.PhysicalAddress[0] = _mac[0] ^ 0x10; // just make something up that's consistent and not part of this net
  908. ipnr.PhysicalAddress[1] = 0x00;
  909. ipnr.PhysicalAddress[2] = (UCHAR)((_deviceGuid.Data1 >> 24) & 0xff);
  910. ipnr.PhysicalAddress[3] = (UCHAR)((_deviceGuid.Data1 >> 16) & 0xff);
  911. ipnr.PhysicalAddress[4] = (UCHAR)((_deviceGuid.Data1 >> 8) & 0xff);
  912. ipnr.PhysicalAddress[5] = (UCHAR)(_deviceGuid.Data1 & 0xff);
  913. ipnr.PhysicalAddressLength = 6;
  914. ipnr.State = NlnsPermanent;
  915. ipnr.IsRouter = 1;
  916. ipnr.IsUnreachable = 0;
  917. ipnr.ReachabilityTime.LastReachable = 0x0fffffff;
  918. ipnr.ReachabilityTime.LastUnreachable = 1;
  919. DWORD result = CreateIpNetEntry2(&ipnr);
  920. if (result != NO_ERROR)
  921. Sleep(250);
  922. else break;
  923. }
  924. for(int i=0;i<8;++i) {
  925. MIB_IPFORWARD_ROW2 nr;
  926. memset(&nr,0,sizeof(nr));
  927. InitializeIpForwardEntry(&nr);
  928. nr.InterfaceLuid.Value = _deviceLuid.Value;
  929. nr.DestinationPrefix.Prefix.si_family = AF_INET; // rest is left as 0.0.0.0/0
  930. nr.NextHop.si_family = AF_INET;
  931. nr.NextHop.Ipv4.sin_addr.s_addr = fakeIp;
  932. nr.Metric = 9999; // do not use as real default route
  933. nr.Protocol = MIB_IPPROTO_NETMGMT;
  934. DWORD result = CreateIpForwardEntry2(&nr);
  935. if (result != NO_ERROR)
  936. Sleep(250);
  937. else break;
  938. }
  939. }
  940. #endif
  941. // Assign or re-assign any should-be-assigned IPs in case we have restarted
  942. {
  943. Mutex::Lock _l(_assignedIps_m);
  944. _syncIps();
  945. }
  946. memset(&tapOvlRead,0,sizeof(tapOvlRead));
  947. tapOvlRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  948. memset(&tapOvlWrite,0,sizeof(tapOvlWrite));
  949. tapOvlWrite.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
  950. wait4[0] = _injectSemaphore;
  951. wait4[1] = tapOvlRead.hEvent;
  952. wait4[2] = tapOvlWrite.hEvent; // only included if writeInProgress is true
  953. ReadFile(_tap,tapReadBuf,sizeof(tapReadBuf),NULL,&tapOvlRead);
  954. bool writeInProgress = false;
  955. ULONGLONG timeOfLastBorkCheck = GetTickCount64();
  956. _initialized = true;
  957. unsigned int oldmtu = _mtu;
  958. setFriendlyName(_friendlyName.c_str());
  959. while (_run) {
  960. DWORD waitResult = WaitForMultipleObjectsEx(writeInProgress ? 3 : 2,wait4,FALSE,2500,TRUE);
  961. if (!_run) break; // will also break outer while(_run) since _run is false
  962. // Check for changes in MTU and break to restart tap device to reconfigure in this case
  963. if (_mtu != oldmtu)
  964. break;
  965. // Check for issues with adapter and close/reopen if any are detected. This
  966. // check fixes a while boatload of Windows adapter 'coma' issues after
  967. // sleep/wake and when adapters are added/removed. Basically if the tap
  968. // device is borked, whack it.
  969. {
  970. ULONGLONG tc = GetTickCount64();
  971. if ((tc - timeOfLastBorkCheck) >= 2500) {
  972. timeOfLastBorkCheck = tc;
  973. char aabuf[16384];
  974. ULONG aalen = sizeof(aabuf);
  975. 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) {
  976. bool isBorked = false;
  977. PIP_ADAPTER_ADDRESSES aa = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(aabuf);
  978. while (aa) {
  979. if (_deviceLuid.Value == aa->Luid.Value) {
  980. isBorked = (aa->OperStatus != IfOperStatusUp);
  981. break;
  982. }
  983. aa = aa->Next;
  984. }
  985. if (isBorked) {
  986. // Close and reopen tap device if there's an issue (outer loop)
  987. break;
  988. }
  989. }
  990. }
  991. }
  992. if ((waitResult == WAIT_TIMEOUT)||(waitResult == WAIT_FAILED)) {
  993. Sleep(250); // guard against spinning under some conditions
  994. continue;
  995. }
  996. if (HasOverlappedIoCompleted(&tapOvlRead)) {
  997. DWORD bytesRead = 0;
  998. if (GetOverlappedResult(_tap,&tapOvlRead,&bytesRead,FALSE)) {
  999. if ((bytesRead > 14)&&(_enabled)) {
  1000. MAC to(tapReadBuf,6);
  1001. MAC from(tapReadBuf + 6,6);
  1002. unsigned int etherType = ((((unsigned int)tapReadBuf[12]) & 0xff) << 8) | (((unsigned int)tapReadBuf[13]) & 0xff);
  1003. try {
  1004. _handler(_arg,(void *)0,_nwid,from,to,etherType,0,tapReadBuf + 14,bytesRead - 14);
  1005. } catch ( ... ) {} // handlers should not throw
  1006. }
  1007. }
  1008. ReadFile(_tap,tapReadBuf,ZT_MAX_MTU + 32,NULL,&tapOvlRead);
  1009. }
  1010. if (writeInProgress) {
  1011. if (HasOverlappedIoCompleted(&tapOvlWrite)) {
  1012. writeInProgress = false;
  1013. _injectPending_m.lock();
  1014. _injectPending.pop();
  1015. } else continue; // still writing, so skip code below and wait
  1016. } else _injectPending_m.lock();
  1017. if (!_injectPending.empty()) {
  1018. WriteFile(_tap,_injectPending.front().data,_injectPending.front().len,NULL,&tapOvlWrite);
  1019. writeInProgress = true;
  1020. }
  1021. _injectPending_m.unlock();
  1022. }
  1023. CancelIo(_tap);
  1024. CloseHandle(tapOvlRead.hEvent);
  1025. CloseHandle(tapOvlWrite.hEvent);
  1026. CloseHandle(_tap);
  1027. _tap = INVALID_HANDLE_VALUE;
  1028. // We will restart and re-open the tap unless _run == false
  1029. }
  1030. } catch ( ... ) {} // catch unexpected exceptions -- this should not happen but would prevent program crash or other weird issues since threads should not throw
  1031. }
  1032. NET_IFINDEX WindowsEthernetTap::_getDeviceIndex()
  1033. {
  1034. MIB_IF_TABLE2 *ift = (MIB_IF_TABLE2 *)0;
  1035. if (GetIfTable2Ex(MibIfTableRaw,&ift) != NO_ERROR)
  1036. throw std::runtime_error("GetIfTable2Ex() failed");
  1037. if (ift->NumEntries > 0) {
  1038. for(ULONG i=0;i<ift->NumEntries;++i) {
  1039. if (ift->Table[i].InterfaceLuid.Value == _deviceLuid.Value) {
  1040. NET_IFINDEX idx = ift->Table[i].InterfaceIndex;
  1041. FreeMibTable(ift);
  1042. return idx;
  1043. }
  1044. }
  1045. }
  1046. FreeMibTable(&ift);
  1047. throw std::runtime_error("interface not found");
  1048. }
  1049. std::vector<std::string> WindowsEthernetTap::_getRegistryIPv4Value(const char *regKey)
  1050. {
  1051. std::vector<std::string> value;
  1052. HKEY tcpIpInterfaces;
  1053. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  1054. char buf[16384];
  1055. DWORD len = sizeof(buf);
  1056. DWORD kt = REG_MULTI_SZ;
  1057. if (RegGetValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,0,&kt,&buf,&len) == ERROR_SUCCESS) {
  1058. switch(kt) {
  1059. case REG_SZ:
  1060. if (len > 0)
  1061. value.push_back(std::string(buf));
  1062. break;
  1063. case REG_MULTI_SZ: {
  1064. for(DWORD k=0,s=0;k<len;++k) {
  1065. if (!buf[k]) {
  1066. if (s < k) {
  1067. value.push_back(std::string(buf + s));
  1068. s = k + 1;
  1069. } else break;
  1070. }
  1071. }
  1072. } break;
  1073. }
  1074. }
  1075. RegCloseKey(tcpIpInterfaces);
  1076. }
  1077. return value;
  1078. }
  1079. void WindowsEthernetTap::_setRegistryIPv4Value(const char *regKey,const std::vector<std::string> &value)
  1080. {
  1081. std::string regMulti;
  1082. for(std::vector<std::string>::const_iterator s(value.begin());s!=value.end();++s) {
  1083. regMulti.append(*s);
  1084. regMulti.push_back((char)0);
  1085. }
  1086. HKEY tcpIpInterfaces;
  1087. if (RegOpenKeyExA(HKEY_LOCAL_MACHINE,"SYSTEM\\CurrentControlSet\\services\\Tcpip\\Parameters\\Interfaces",0,KEY_READ|KEY_WRITE,&tcpIpInterfaces) == ERROR_SUCCESS) {
  1088. if (regMulti.length() > 0) {
  1089. regMulti.push_back((char)0);
  1090. RegSetKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey,REG_MULTI_SZ,regMulti.data(),(DWORD)regMulti.length());
  1091. } else {
  1092. RegDeleteKeyValueA(tcpIpInterfaces,_netCfgInstanceId.c_str(),regKey);
  1093. }
  1094. RegCloseKey(tcpIpInterfaces);
  1095. }
  1096. }
  1097. void WindowsEthernetTap::_syncIps()
  1098. {
  1099. // assumes _assignedIps_m is locked
  1100. if (!_initialized)
  1101. return;
  1102. std::vector<InetAddress> haveIps(ips());
  1103. for(std::vector<InetAddress>::const_iterator aip(_assignedIps.begin());aip!=_assignedIps.end();++aip) {
  1104. if (std::find(haveIps.begin(),haveIps.end(),*aip) == haveIps.end()) {
  1105. MIB_UNICASTIPADDRESS_ROW ipr;
  1106. InitializeUnicastIpAddressEntry(&ipr);
  1107. if (aip->isV4()) {
  1108. ipr.Address.Ipv4.sin_family = AF_INET;
  1109. ipr.Address.Ipv4.sin_addr.S_un.S_addr = *((const uint32_t *)aip->rawIpData());
  1110. ipr.OnLinkPrefixLength = aip->netmaskBits();
  1111. if (ipr.OnLinkPrefixLength >= 32)
  1112. continue;
  1113. } else if (aip->isV6()) {
  1114. ipr.Address.Ipv6.sin6_family = AF_INET6;
  1115. memcpy(ipr.Address.Ipv6.sin6_addr.u.Byte,aip->rawIpData(),16);
  1116. ipr.OnLinkPrefixLength = aip->netmaskBits();
  1117. if (ipr.OnLinkPrefixLength >= 128)
  1118. continue;
  1119. } else continue;
  1120. ipr.PrefixOrigin = IpPrefixOriginManual;
  1121. ipr.SuffixOrigin = IpSuffixOriginManual;
  1122. ipr.ValidLifetime = 0xffffffff;
  1123. ipr.PreferredLifetime = 0xffffffff;
  1124. ipr.InterfaceLuid = _deviceLuid;
  1125. ipr.InterfaceIndex = _getDeviceIndex();
  1126. CreateUnicastIpAddressEntry(&ipr);
  1127. }
  1128. if (aip->isV4()) {
  1129. char ipbuf[64];
  1130. std::string ipStr(aip->toIpString(ipbuf));
  1131. std::vector<std::string> regIps(_getRegistryIPv4Value("IPAddress"));
  1132. if (std::find(regIps.begin(), regIps.end(), ipStr) == regIps.end()) {
  1133. std::vector<std::string> regSubnetMasks(_getRegistryIPv4Value("SubnetMask"));
  1134. regIps.push_back(ipStr);
  1135. regSubnetMasks.push_back(aip->netmask().toIpString(ipbuf));
  1136. _setRegistryIPv4Value("IPAddress", regIps);
  1137. _setRegistryIPv4Value("SubnetMask", regSubnetMasks);
  1138. }
  1139. }
  1140. }
  1141. }
  1142. } // namespace ZeroTier