WindowsEthernetTap.cpp 47 KB

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